Using the :nth child selector in CSS3

Posted on Wed, November 28, 2012 in Web Design, by Kevin Carpenter

There is a CSS selector called nth-child. If you put simply a number in the parentheses, it will match only that number element. For example, here is how to select only the 3rd element: The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.

ul li:nth-child(3{ 
color#ccc;

This selects the 3rd element in a list of related elements and changes its color. nth-child also accepts two keywords in the parentheses spot: even and odd. Those should be pretty obvious. "Even" selects even numbered elements, like the 2nd, 4th, 6th, etc. "Odd" selects odd numbered elements, like 1st, 3rd, 5th, etc.

ul li:nth-child(even{ 
color#ccc;
}
ul li
:nth-child(odd{
color
#ccc;
It is also possible to simply select the last element in a list.
ul lilast-child {
color
green;

Conclusion:

As you can see, CSS3 makes it a lot easier to select specific elements in a list and style them accordingly in an intuitive fashion. Interestingly enough, the nth-child selector can also be applied to divs in the same way. If you are interested in playing around with the nth-child property, go here. CSS-tricks has put together a very cool nth Tester.

Demo

Below, are some examples of using the nth child selector on paragraphs:

CSS

ul li:nth-child(even{ 
colorrgb(0,0,255);
}
ul li
:nth-child(odd{
color
rgb(0,150,0);
}
ul li
:last-child {
color
rgb(139,134,78);

Result

Support:

The :nth-child() selector is supported in all major browsers, except IE8 and earlier.

Tell Us About Your Project

Invalid phone number