51

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.

Markus Hedlund
  • 23,374
  • 22
  • 80
  • 109
  • I don't believe there is a way you can select the child of a class with these pseudo-class selectors. Is it always the 4th heading in a list or is it always the 2nd instance of class .heading that you want to style? If always 4th the below answer should work fine although you could also use nth-of-type. – KryptoniteDove Oct 07 '11 at 13:21
  • You make your own life difficult if you don't fix this problem at the markup/semantic/html level. Using nested `ul`s will allow you to do exactly what you want with CSS2 selectors. – Marcel Jackwerth Oct 07 '11 at 13:23

4 Answers4

36

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.

Marcus Olsson
  • 2,485
  • 19
  • 35
21

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;}
Deepak Rai
  • 2,163
  • 3
  • 21
  • 36
Santosh Verma
  • 235
  • 2
  • 3
11
ul li.heading:nth-last-child(2)

2 means you know how many of <li> are after your <li class="heading"> in our case it is second from bottom.

T J
  • 42,762
  • 13
  • 83
  • 138
boo
  • 111
  • 1
  • 2
6

This is because li.heading is not the last-child nor is it the second child. It is the first and fourth child of the ul

Give this a try:

  ul li.heading:nth-child(4) {
    background: black;
}
Jared
  • 12,406
  • 1
  • 35
  • 39