CSS 使用 :last-child 和类选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7687597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:50:09  来源:igfitidea点击:

Using :last-child with class selector

css

提问by Znarkus

I want to style the last/second .heading.

我想设计 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>

Neither

两者都不

ul li.heading:last-child {
    background: black;
}

nor

也不

ul li.heading:nth-child(2) {
    background: black;
}

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.

为我工作。为什么,我该如何应用样式<li>呢?似乎伪类选择器不适用于类选择器。这很奇怪,因为我可以发誓我以前用过它。

Update:Oops, totally forgot the jsfiddle.

更新:糟糕,完全忘记了 jsfiddle

采纳答案by Marcus Olsson

Your statement was: "I want to style the last/second .heading."

您的声明是:“我想为最后/第二个 .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>

And the CSS:

和 CSS:

ul li.heading:last-child {
    background: black;
}
ul li.heading:nth-child(2) {
    background: black;
}

Else, with your current html-code, you would write:

否则,使用您当前的 html 代码,您将编写:

ul li.heading:nth-child(4) {
    background: black;
}
ul li.heading:nth-child(1) {
    background: black;
}

I understand your thought, but the lis with the class "heading" isn't the second or last child.

我理解你的想法,但是带有“标题”类的 lis 不是第二个或最后一个孩子。

回答by boo

ul li.heading:nth-last-child(2)

2 means you know how many of <li>are after your <li class="heading"> in our case it is second from bottom.

2 意味着您知道在您的 <li class="heading"> 之后有多少 <li> 在我们的例子中它是倒数第二个。

回答by Jrod

This is because li.headingis not the last-child nor is it the second child. It is the first and fourth child of the ul

这是因为li.heading它不是最后一个孩子,也不是第二个孩子。它是第一个和第四个孩子ul

Give this a try:

试试这个:

  ul li.heading:nth-child(4) {
    background: black;
}

回答by Santosh Verma

you can use ul li.heading:nth-of-type, It will consider only heading class as per your html css will

您可以使用ul li.heading:nth-of-type,它只会根据您的 html css 考虑标题类

li.heading:nth-of-type(2){ background: black;}

or

或者

li.heading:last-of-type{ background: black;}