我有一个结构:
<div id="div">
<ul class="ul">
<li class="li_one">
</li>
<li class="li_two">
</li>
</ul>
</div>
我想使用伪选择器将 background:red
设置为第二个 li
元素(类“li_two”),并希望从最外层的 div 开始。我正在尝试这样:
#div > ul:nth-child(1) { background:red; } // works but wrong, sets background to ul
#div ul:last-child { background:red; } // doesn't set to any element
#div ul:first-child { background:red; } // again sets to ul but not to li
#div [class=li_two] { background:red; } // only this one works fine
是否可以使用 :nth-child
或 :last-child
从 #div
将样式设置为 li_two
code> 或 :first-child
选择器?怎么做?
最佳答案
#div li:last-child
您的第二个选项几乎是正确的 :) 我认为您误解了 last-child 的作用。 xx:last-child 不选择元素xx的最后一个子元素;它选择作为其父项的最后一个子项的每个 xx 元素。
关于css - nth-child 或 first/last-child 选择器不起作用。如何正确应用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12647925/