【问题标题】:Get the n'th element relative to it's parent with CSS [closed]使用CSS获取相对于其父元素的第n个元素[关闭]
【发布时间】:2013-11-07 23:18:38
【问题描述】:

我想相对于它的父元素而不是相对于文档来设置第 n 个元素的样式。 明白了:

css:

ul li:nth-child(2n){ background: #fff; }

html:

<ul>
<li></li> // background is white
<li></li>
<li></li> // background is white
</ul>
<ul>
<li></li>
<li></li> // background is white
<li></li>
</ul>

在这种情况下,每个第二个元素获取一个白色背景,从文档开始计数,元素获取父元素“ul”无关紧要。

现在我希望在每个“ul”元素处重新设置计数。结果应如下所示:

<ul>
<li></li> // background is white
<li></li>
<li></li> // background is white
</ul>
<ul>
<li></li> // background is white
<li></li>
<li></li> // background is white
</ul>

谁能帮帮我?

【问题讨论】:

标签: css css-selectors


【解决方案1】:
ul > li:nth-child(2n) {background: #fff;}

不过,这不应该是必要的。您的原始代码工作正常:http://jsfiddle.net/isherwood/5MKtK

【讨论】:

    【解决方案2】:

    使用这个nth-of-type 和直接后代选择器

    ul >li:nth-of-type(2n){ background: #fff; }
    

    工具:http://css-tricks.com/examples/nth-child-tester/

    【讨论】:

    • 这是多余的,因为li 是唯一可以有效包含在ul 中的元素。
    猜你喜欢
    • 2023-03-13
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 2021-11-02
    • 1970-01-01
    • 2011-06-27
    相关资源
    最近更新 更多