Using :last-child with class selector

Your statement was: "I want to style the last/second .heading."

That would mean that you would have to write your code like this:

<ul>
    <li class="heading">Hello world</li>
    <li class="heading">Hello world</li>
    <li class="heading">Hello world</li>
    <li class="heading">Hello world</li>
    <li class="heading">Hello world</li>
</ul>

And the CSS:

ul li.heading:last-child {
    background: black;
}
ul li.heading:nth-child(2) {
    background: black;
}

Else, with your current html-code, you would write:

ul li.heading:nth-child(4) {
    background: black;
}
ul li.heading:nth-child(1) {
    background: black;
}

I understand your thought, but the lis with the class "heading" isn't the second or last child.


you can use ul li.heading:nth-of-type, It will consider only heading class as per your html css will

li.heading:nth-of-type(2){ background: black;}

or

li.heading:last-of-type{ background: black;}

Tags:

Css