CSS: :last-child on list item

流过昼夜 提交于 2019-12-10 02:02:20

问题


If a ul has li items with multiple classes, is it possible to get the last item of a specific class using :last-child?

For example, consider following:

<ul class="test">
    <li class="one">
    <li class="one">
    <li class="one">
    <li class="two">
    <li class="two">
</ul>

I want to add some style to the last li having class "one" (ie. third in the list).

I tried following and it does not work.

ul.test li.one:last-child 

回答1:


That's not possible yet.

  • :last-child selects the last child, regardless of the tag name, etc.
  • The possible alternative, :last-of-type selects the last occurrence of a tag. It ignores the class name, etc.

Your only option is to add a specific class name to that element, or use JavaScript to add this class name.




回答2:


Instead of giving class for each li, you can go for nth child where you can assign the style by li number.

If you want to give the separate css for your 3rd li then you need to write

li:nth-child(3) {
    color: green;   
}



回答3:


You can do it using jquery: http://jsfiddle.net/surendraVsingh/HyAhL/2/

Jquery code:

var n = $('.one').length;
$('.one').eq(n-1).css('color', 'red');


来源:https://stackoverflow.com/questions/11326915/css-last-child-on-list-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!