如何选择“最后一个孩子"?在 CSS 中使用特定的类名?

如何选择“最后一个孩子

问题描述:

<ul>
    <li class="list">test1</li>
    <li class="list">test2</li>
    <li class="list">test3</li>
    <li>test4</li>
</ul>

如何选择具有班级名称的最后一个孩子":list?

How do I select the "last child" with the class name: list?

<style>
    ul li.list:last-child{background-color:#000;}
</style>

我知道上面的例子行不通,但有没有类似的东西行得通?

I know the example above doesn't work, but is there anything similar to this that does work?

重要提示:

a) 我不能使用 ul li:nth-child(3),因为它也可能排在第四或第五位.

a) I can't use ul li:nth-child(3), because it could happen that it's on the fourth or fifth place too.

b) 没有 JavaScript.

b) No JavaScript.

我建议你利用这样一个事实,你可以像这样为一个元素分配多个类:

I suggest that you take advantage of the fact that you can assign multiple classes to an element like so:

<ul>
    <li class="list">test1</li>
    <li class="list">test2</li>
    <li class="list last">test3</li>
    <li>test4</li>
</ul>

最后一个元素和它的兄弟元素一样有 list 类,但也有 last 类,你可以用它来设置你想要的任何 CSS 属性,如下所示:>

The last element has the list class like its siblings but also has the last class which you can use to set any CSS property you want, like so:

ul li.list {
    color: #FF0000;
}

ul li.list.last {
    background-color: #000;
}