Skip to main content

nth-child explained

Published on 12th August 2013

The :nth-child CSS pseudo-class is one of the most powerful and useful pseudo classes. Having built a number of responsive websites over the last year, I have learnt that understanding and using :nth-child to its full potential will add a valuable tool to your responsive CSS arsenal.

So what does it do?

The :nth-child CSS pseudo-class selects elements based on their positions within a parent element's list of child elements.

It accepts an argument, (n), which can be a keyword, an integer (number), or an expression (an+b) which selects a particular combination of child elements.

start off simple - keyword

The two keywords are odd and even which will select every other child element as shown below

li:nth-child(odd) {
 background-color: #b2424b;
}
li:nth-child(even) {
 background-color: #b2424b;
}

See the Pen ycnjg by Matt Harris (@matt-harris) on CodePen.

Moving on - Integer

The second argument we can pass is an Integer. In the example below we will select the fourth list item

li:nth-child(4) {
 background-color: #b2424b;
}

See the Pen hJsxg by Matt Harris (@matt-harris) on CodePen.

The tricky one - expression

We can also pass an expression (an+b) which selects a particular combination of child elements. a and b are always numbers and n is always n.

:nth-child(an+b) explanation

b is the starting offset. It determines which element is selected first. a is the iteration value - the elements to select after the first one has been selected. a and b can be a negative numbers. If you are selecting every item after a certain starting point we can leave off the value for a.

In this example we will start with the fourth list element (b = 4) and then select every third list item after (a = 3).

li:nth-child(3n+4) {
 background-color: #b2424b;
}

To select every element after a starting point we don't need to include a value for a. In this example we will select every list item including and after four.

li:nth-child(n+4) {
 background-color: #b2424b;
}

We can also give a and b negative numbers. For example if we want to select every list item including eight and before we can use the following.

li:nth-child(-n+8) {
 background-color: #b2424b;
}

An example of using a negative b value would be.

li:nth-child(5n+-2) {
 background-color: #b2424b;
}

See the Pen pobvt by Matt Harris (@matt-harris) on CodePen.

It's tricky

Getting your head around :nth-child can seem rather confusing at first. Stick with it and practice using different combinations and it will become easier and will make you a faster and more efficient coder.