Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: :last-child on list item

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 
like image 450
user1355300 Avatar asked Jul 04 '12 10:07

user1355300


People also ask

How do you select the last element in a list in CSS?

: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.

How do you find the last child of an element?

To get the last child of a specific HTML Element, using JavaScript, get reference to this HTML element, and read the lastElementChild property of this HTML Element. lastElementChild property returns the last child of this HTML Element as Element object.


2 Answers

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.

like image 200
Rob W Avatar answered Sep 20 '22 06:09

Rob W


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;   
}
like image 35
Sowmya Avatar answered Sep 23 '22 06:09

Sowmya