Dustin Poissant
Dustin Poissant

Reputation: 3418

CSS selector for selecting the last two children, without knowing how many items are in the list

I have an unordered list. It sometimes contains 4, 5, 6, or 7 items. I would like to know if there is a CSS selector to select the last two items. I realize that :last-child will get me the last item. Is there a "second to last child" selector? or "number of children -2" selector?

HTML:

<ul>
  <li>First Item</li>
  <li>Second Item</li>
  <li>Second from Last Item</li>
  <li>Last Item</li>
<ul>

CSS:

ul li:last-child, ul li:last-child-1 {
  // Do something
}

I realize :last-child-1 is not a selector but im hoping there is something similar out there. Any help would be greatly apprecialted.

Upvotes: 5

Views: 1415

Answers (2)

Nico O
Nico O

Reputation: 14102

Go for :nth-last-child

http://jsfiddle.net/pQmXM/1/

ul li:nth-last-child(1),
ul li:nth-last-child(2)
{
    color: red;
}

Upvotes: 6

Adrift
Adrift

Reputation: 59779

ul li:nth-last-child(-n + 2) {
    /* .. */
}

Upvotes: 13

Related Questions