Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 448
Dustin Poissant Avatar asked Dec 04 '22 07:12

Dustin Poissant


2 Answers

ul li:nth-last-child(-n + 2) {
    /* .. */
}
like image 65
Adrift Avatar answered May 25 '23 05:05

Adrift


Go for :nth-last-child

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

ul li:nth-last-child(1),
ul li:nth-last-child(2)
{
    color: red;
}
like image 45
Nico O Avatar answered May 25 '23 05:05

Nico O