Dave Woods - Freelance Web Design Warwickshire

How to use the :nth-child selector

This tutorial explains how the :nth-child pseudo-selector can be used to style specific HTML elements depending on their position within your markup.

:nth child format

The format of the :nth-child selector is pretty straight forward and the only difference concerns what value is placed within the brackets.

ul li:nth-child(4n) { background: #ccc; }

In the above example, the “4n” is the value that determines which element is given the background colour.

Odd and even rows using CSS

The :nth-child selector accepts two keywords, odd and even. It’s pretty self explanatory as to what these do and they’d be used in the following format.

ul li:nth-child(odd) { background: red; }
ul li:nth-child(even) { background: blue; }

All odd numbered li’s would have a red background, whilst all even li’s would have a blue background.

:nth-child and numerical values

Using numbers can get a little more complicated. To select a single element you’d simply use a single number:

ul li:nth-child(3) { background: #ccc; }

The above example would simply select the 3rd element in your list.

However, the more common use for :nth-child is to select elements in a specific pattern. For example, you may want to select every fourth element.

In order to do this you’d need to do the following:

ul li:nth-child(4n) { background: #ccc; }

To see how this works you’ll need to do a little bit of algebra to understand what “n” represents. Essentially, “n” starts at zero and counts upwards until there are no more matches.

Therefore for the (4n) value we get the following:

(4 x 0) = 0 = no match
(4 x 1) = 4 = 4th Element
(4 x 2) = 8 = 8th Element
(4 x 3) = 12 = 12th Element
(4 x 4) = 16 = 16th Element… and so on.

Browser compatibility

All modern browsers support :nth-child including IE9 and upwards so we’re almost at the stage where you don’t even have to consider whether your target audience has support.

However, you may need to consider that IE8 has no support for nth-child. If you’re using it for odd/even row colours then I’d personally use :nth-child without hesitation, however if it’s for removing margin, border or padding from elements and the layout is heavily dependant on it then you may be better considering the jQuery method of applying :nth-child.

Further reading and tools