【问题标题】:E > E:nth-child(2) pattern doesn't work. How to solve it?E > E:nth-child(2) 模式不起作用。如何解决?
【发布时间】:2012-11-21 23:16:41
【问题描述】:

我有一个结构:

<div id="outer">
    <div> <!-- first div -->
        <div>  <!-- second div -->
        </div>
    </div>
</div>

我想使用 E &gt; E:nth-child(n) 模式将样式应用于 firstsecond div。但它不适用于 second div,仅适用于 first

/* this works */
#outer > div:nth-child(1) {
    border: 1px solid red;
    padding: 10px;
}

/* this doesn't work */
#outer > div:nth-child(2) {
    border: 1px solid green;
    padding: 10px
}

为什么不工作?我怎样才能让它发挥作用?

【问题讨论】:

  • 这是因为每个内部div 是其父div 的第一个也是唯一的孩子...
  • 因为第二个div不是#outer的孩子

标签: css css-selectors pseudo-class


【解决方案1】:

试试这个:

#outer > div:nth-child(1) > div:nth-child(1)

【讨论】:

  • 谢谢,是的,这行得通。 #outer &gt; div &gt; div 有效,#outer &gt; div:nth-child(1) &gt; div:nth-child(1) 也有效。
  • 我删除了旧的,因为它与您提到的模式不匹配。祝你好运!
【解决方案2】:

第二个 div 不是来自#outer 的直接子级。因此,您的选择器 #outer &gt; div 不会影响第二个 div,因为 &gt; 仅选择 direct 子级。 也许你可以使用

/* this works */
#outer > div:nth-child(1) {
    border: 1px solid red;
    padding: 10px;
}

/* this should also work */
#outer > div:nth-child(1) > div:nth-child(1) {
    border: 1px solid green;
    padding: 10px
}

【讨论】:

  • 不仅是&gt; 选择器,还有:nth-child() 选择器。也许如果他们将其称为:nth-direct-child()...
  • 感谢您的解释。现在我看到了区别。
猜你喜欢
  • 2021-09-29
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多