Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using :last-child with class selector

Tags:

css

I want to style the last/second .heading.

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

Neither

ul li.heading:last-child {     background: black; } 

nor

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

works for me. Why, and how can I apply styles to that <li>? It seems pseudo-class selectors doesn't work with class selectors. Which is weird since I could've sworn I'd used it before.

Update: Oops, totally forgot the jsfiddle.

like image 448
Znarkus Avatar asked Oct 07 '11 12:10

Znarkus


People also ask

How do I target the last child of a table in CSS?

The :last-child selector is a pseudo-class that allows you to target an element that is the last child element within its parent. See also :first-child, :nth-child, :nth-last_child, and :only-child selectors.


1 Answers

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.

like image 167
Marcus Olsson Avatar answered Sep 18 '22 17:09

Marcus Olsson