offline version v3


237 of 298 menu

nth-child pseudo-class

The nth-child pseudo-class selects an element that is the nth child of its parent.

Syntax

selector:nth-child(number | odd | even | expression) { }

Values

Value Description
number A positive number starting with 1. Specifies the number of the element we want to access. Numbering of elements starts from 1.
odd Odd elements.
even Even elements.
expression You can create special expressions with the letter n, which stands for all integers from zero (not one) to infinity. So, 2n means all even numbers (starting from the second).
How to understand this? We substitute into n sequentially the numbers from 0 and so on: if n = 0, then 2n will give 0 - there is no such element (numbering of elements starting from 1), if n = 1, then 2n gives 2 - the second element, if n = 2, 2n gives 4 - the fourth element. If you write 3n, it will be every third element (starting from the third), and so on.

Example

In this example, we will make red the li that is the 4th child of its parent:

<ul> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> </ul> li:nth-child(4) { color: red; }

:

Example

Now let’s make all even li red:

<ul> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> </ul> li:nth-child(even) { color: red; }

:

Example

Now we make all odd li red:

<ul> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> </ul> li:nth-child(odd) { color: red; }

:

Example

Now we’ll make every third li red (starting from the third):

<ul> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> </ul> li:nth-child(3n) { color: red; }

:

Example

The selector can specify a range of elements. Let's say you have a list of 20 elements and you need to select elements from 7th to 14th inclusive. It can be done like this:

<ol> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> </ol> li:nth-child(n+7):nth-child(-n+14) { color: red; }

:

enru