Skip to content

Using the :nth child selector in CSS3

By GRAYBOX Alumni

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.

[code] ul li:nth-child(3) { color: #ccc; } [/code] 

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.

[code] ul li:nth-child(even) { color: #ccc; } ul li:nth-child(odd) { color: #ccc; } [/code] 

It is also possible to simply select the last element in a list.

[code] ul li: last-child { color: green; } [/code] 

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

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


Result

Itemized List

Support:

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

Blog & Events

Featured Work