使用:last-child类选择器 [英] Using :last-child with class selector
问题描述
我想制作最后一个/第二个 .heading
。
I want to style the last/second .heading
.
<ul>
<li class="heading">Hello world</li>
<li>Hello world</li>
<li>Hello world</li>
<li class="heading">Hello world</li>
<li>Hello world</li>
</ul>
ul li.heading:last-child {
background: black;
}
或
ul li.heading:nth-child(2) {
background: black;
}
适用于我。为什么,如何应用样式到< li>
?看来伪类选择器不工作类选择器。
works for me. Why, and how can I apply styles to that <li>
? It seems pseudo-class selectors doesn't work with class selectors. Which is weird since I could've sworn I'd used it before.
更新:糟糕,完全忘记了 the jsfiddle 。
推荐答案
你的声明是:我想要风格的最后/第二个。
Your statement was: "I want to style the last/second .heading."
这意味着你必须这样写你的代码:
That would mean that you would have to write your code like this:
<ul>
<li class="heading">Hello world</li>
<li class="heading">Hello world</li>
<li class="heading">Hello world</li>
<li class="heading">Hello world</li>
<li class="heading">Hello world</li>
</ul>
和CSS:
ul li.heading:last-child {
background: black;
}
ul li.heading:nth-child(2) {
background: black;
}
另外,对于当前的html代码,您可以这样写:
Else, with your current html-code, you would write:
ul li.heading:nth-child(4) {
background: black;
}
ul li.heading:nth-child(1) {
background: black;
}
我理解你的想法,但lis与类headingisn'第二个或最后一个孩子。
I understand your thought, but the lis with the class "heading" isn't the second or last child.
这篇关于使用:last-child类选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!