CSS: :last-child on list item

2020-08-12 17:59发布

问题:

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');