Patrick Desjardins Blog
Patrick Desjardins picture from a conference

CSS and the selector nth-child

Posted on: 2012-07-27

You may want to have special style for specific position. Maybe you want to have the first division different or having every 3 rows something different.

This can be done with nth-child selector of CSS.

Let's start with a small example :

ul>li:nth-child(3) { 
  color: red; 
} 

This example takes the third li element that is directly under an ul element and make it's font color to red.

The parameter, when specified with an integer, represent the position of the occurrence of the element. In the example above, 3 is specified, so the third element will be red.

nth-child is power full because you can use the variable "n" to specify the index of the element.

ul>li:nth-child(2n+1) { 
  background-color: red; 
} 

This second example of nth-child has 2n+1 has parameter. That mean that it will start at the position 1 (every sequence start at 1 not 0) and 2n mean 2 multiply by the index.

So if we have the following code:

<ul> 
  <li>n=0</li> 
  <li>n=1</li> 
  <li>n=2</li> 
  <li>n=3</li> 
  <li>n=4</li> 
  <li>n=5</li> 
</ul> 

2n+1 will be for the first line: 2x0+1 = 1.

So, the first li will have the style, the first one will be 1. Then we have 2x1+1 = 3.

The second row won't have any style, the third one yes and so on.

To conclude, you have to remember that n start at 0 but the first element is 1. As we have seen with the ul and li example, the n=0 was coloured because n=0+1 = one, which is the first li of the ul collection.