CSS :nth-child() Pseudo Class

The :nth-child() pseudo-class selects and adds styles to elements based on their index.

The :nth-child() can be specified by a number, a keyword, or a formula.

Keyword values

odd

Represents those elements whose numeric position is odd (e.g 1, 3, 5, 7 etc.).

even

Represents those elements whose numeric position is even (e.g 2, 4, 6, 8 etc.).

Functional notation

<An+B>

Represents those elements whose numeric position matches the pattern An+B (for every positive integer or zero value of n). The first element’s index is 1, and n in the formula starts from 0. The values A and B must be integers.

Version

Selectors Level 4

Selectors Level 3

Syntax

:nth-child() {
  css declarations;
}

Example of the :nth-child selector:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p:nth-child(3) {
        background: #ccc;
      }
    </style>
  </head>
  <body>
    <h2>:nth-child selector example</h2>
    <div>
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
      <p>Paragraph 3</p>
      <p>Paragraph 4</p>
    </div>
  </body>
</html>

Example of "odd" and "even" keywords:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p:nth-child(odd) {
        background: #1c87c9;
        color: #eeeeee;
      }
      p:nth-child(even) {
        background: #666666;
        color: #eeeeee;
      }
    </style>
  </head>
  <body>
    <p>The first paragraph.</p>
    <p>The second paragraph.</p>
    <p>The third paragraph.</p>
  </body>
</html>

Browser support

chrome edge firefox safari opera
4.0+ 12.0+ 3.5+ 3.2+ 10.0+

Practice Your Knowledge

What is the function of nth-child() selector in CSS?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.