【问题标题】:Select odd elements except the first-child选择除第一个孩子以外的奇数元素
【发布时间】:2014-05-23 12:34:20
【问题描述】:

我有这样的 div 元素

<div id="container">
    <div id="content">
        <div class="arrow"></div>
    </div>
    <div id="content">
        <div class="arrow"></div>
    </div>
    <div id="content">
        <div class="arrow"></div>
    </div>
    <div id="content">
        <div class="arrow"></div>
    </div>
</div>

我想选择第一个孩子,但我有这样的 css

#container #content:nth-child(odd) .arrow {
    background: red;
}
#container #content:nth-child(even) .arrow {
    background: green;
}
#container #content:first-child .arrow {
    background: pink;
}

但是第一个孩子是红色的,因为第一个孩子是奇数。

我试过用这个,但我不知道它是否会起作用,但它没有

#container #content:nth-child(odd):not(:first-child) .arrow {
    background: red;
}

但是,第一个 div 的箭头仍然是红色的。

我做错了什么?

【问题讨论】:

标签: html css css-selectors


【解决方案1】:

:nth(odd) 只是:nth(2n+1) 的快捷方式,如果没记错的话,所以我认为:nth(2n+3) 可能有用。

【讨论】:

  • 确实,需要明确的是,:nth-child(2n+3) 将替代 :nth-child(odd):not(:first-child)。
【解决方案2】:

试试这个:

#container #content:first-child .arrow {
    background: pink!important;
}

优先考虑那个值

问候!

【讨论】:

  • 使用!important 是一个禁忌,除非你有充分的理由这样做。
  • 你的意思是我没有?当两个或多个类匹配同一个元素时,!important 优先考虑该声明
  • 这就是它的作用,当然,但这并不是使用它的好理由,因为在大多数情况下有更好的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
相关资源
最近更新 更多