CSS :nth-child() Selector

CSS :nth-child(n) selector selects every element that is the nth child of its parent element.

Here n can be a:

  • Number – Like 1, 2, 3, 4, 5, …. and so on
  • Keyword – even or odd
  • Formula – Like 2n+1, 2n+2, etc.

For example, if you set n=3, It would select every 3rd element of its parent and if you set n=4 it would select every 4th element of its parent.

In the following example, the :nth-child(3) selector selects every 3rd element of its parent(irrespective of its type) and sets a yellow color background to it.

Example:

:nth-child(3){
   background: yellow;
}

With keywords like even & odd, you can select every child that is at even or odd positions inside its parent.

The :nth-child() selector in the below example will set a yellow background to every <p> element that is at the odd position and a cyan color background to every <p> element that is at the even position.

Example:

p:nth-child(odd){
   background: yellow;
}
p:nth-child(even){
   background: cyan;
}

The :nth-child() selector can also select elements that satisfy a particular formula in the form of (an+b).

For example, (2n + 0) will select every element that is at even positions(2, 4, 6,…) . Similarly (2n+1) will select every element that is at the odd positions(1, 3, 5, 7,…).

Here is a working example:

Example:

p:nth-child(2n+1){
   background: yellow;
}
p:nth-child(2n+0){
   background: cyan;
}

CSS Syntax

The syntax of the :nth-child() selector is as follows:

:nth-child(N){
   CSS Styles;
}

Browser Support

The number in each cell of the table specifies the first version of the browser that fully supports the :nth-child() selector.

Selector
:nth-child()4.09.03.53.29.6

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.