CSS :nth-child() Pseudo Class

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

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

Version

CSS3

Syntax

:nth-child() {
css declarations;
}

Example

<!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>

In this example, "odd" and "even" keywords are used:

Example

<!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>

Practice Your Knowledge

The :nth-child() can't be specified by a




Related articles