如何选择“最后一个孩子"?在 CSS 中使用特定的类名? [英] How do I select the "last child" with a specific class name in CSS?

查看:34
本文介绍了如何选择“最后一个孩子"?在 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;
}

这篇关于如何选择“最后一个孩子"?在 CSS 中使用特定的类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆