【问题标题】:Understanding CSS child selector [duplicate]了解 CSS 子选择器 [重复]
【发布时间】:2017-07-26 17:13:14
【问题描述】:

我无法使用下面的html结构的nth-childnth-of-type

<div class="wrapper">
    <div class="child_1">Child 1</div>
    <div> Not child 1 </div>
    <div class="child_1">Child 1</div>
    <div class="child_1">Child 1</div>
</div>

我想做的是选择第二个child_1,但我找不到方法。 有人给我答案吗?

【问题讨论】:

  • 这是题外话,伙计。你应该阅读一些基本的 CSS 教程。
  • .wrapper div.child_1:nth-child(2)

标签: html css css-selectors


【解决方案1】:

您不能为课程选择nth-of-type。您必须改为定位 div

来自 MDN:

nth-of-type

nth-child

.wrapper div:nth-child(3) {
  color: red;
}
<div class="wrapper">
  <div class="child_1">Child 1</div>
  <div> Not child 1 </div>
  <div class="child_1">Child 1</div>
  <div class="child_1">Child 1</div>
</div>

【讨论】:

  • nth-childnth-of-type 是伪类(CSS3 选择器标准)。根据 CSS3 标准,只接受伪类元素,而伪类是不可能的。
  • @ovokuro:你能找到这个jsfiddle.net/hv3vqazk。我看到我可以在这里按班级选择。
  • @freeman167 jsfiddle.net/afsz49e2 -- 你没有选择课程。该类的类型为div。那就是被选中。看我的小提琴...
【解决方案2】:

这将完成您的工作。

.wrapper .child_1:nth-child(3){
  background:red;
}
    <div class="wrapper">
        <div class="child_1">Child 1</div>
        <div> Not child 1 </div>
        <div class="child_1">Child 1</div>
        <div class="child_1">Child 1</div>
    </div>

但是,如果您想了解child 选择。 有几种选择。比如nth-childnth-of-typefirst-childlast-child

在此示例中,您不能使用nth-of-type,但可以使用其余部分。如果这是一个较长的子组,并且您无法选择底部,则可以使用。

.wrapper .child_1:last-child{
  background:red;
}

如果你想选择second last child,你可以使用:

.wrapper .child_1:last-child(2){
  background:red;
}

这也来自 top 使用 first-child 子选择器。太棒了

【讨论】:

  • 虽然这会起作用,但选择器实际上是针对div,而不是类。 (我没有投反对票)
  • 他想在 Q 中选择 `2nd child_1`。所以我的答案是正确的。如果课程不在那里,我的答案将不起作用。那么为什么 downvote,如果答案是正确的那么请不要对你们投反对票。不要破坏 Stackoverflow 的价值。
猜你喜欢
  • 2015-07-18
  • 2010-10-05
  • 2018-08-19
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多