Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I choose the last 2 items in a list with css nth-child?

Is it possible? If not, is there a way to do it with jQuery?

like image 480
John Avatar asked Jul 07 '11 01:07

John


People also ask

How do I select a specific Nth child in CSS?

Definition and UsageThe :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

How do you select all child elements except last?

When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.


1 Answers

It is possible with CSS3. Consider the markup:

<ul>     <li><a href="">First item</a></li>     <li>Second item</li>     <li><a href="">Test</a></li>     <li><a href="">Test</a></li>     <li><a href="">Pre-last item</a></li>     <li><a href="">Last item</a></li> </ul> 

To choose the last two LI elements you do:

ul > li:nth-last-of-type(-n+2) {     background: green; } 

Works in all contemporary browsers including IE9, but excluding IE8 and below. To add support for those browsers, you might consider using Selectivizr.js

like image 129
spliter Avatar answered Oct 01 '22 03:10

spliter