CSS Nth Selector

The :nth-child(n) selector is used to select elements based on their position within a parent element's list of children. The n can be a number, a keyword, or a formula, and it determines which elements are selected based on their ordinal position.

Syntax:

selector:nth-child(n) {
/* CSS Property */
}

The n in the parentheses can be a number, a keyword (such as odd or even), or a functional notation (such as An+B).

Keywords: odd and even

Odd: Matches elements in odd positions (1, 3, 5, etc.).

p:nth-child(odd) {
background-color: lightblue;
}

Even: Matches elements in even positions (2, 4, 6, etc.).

p:nth-child(even) {
background-color: lightgreen;
}

Functional Notation: An+B

The functional notation An+B allows for more complex patterns, where:

• A is an integer that represents the step size.

• n is a counter starting from 0.

• B is an integer that represents the offset.

Example:

Every 3rd element (starting from the 1st):

li:nth-child(3n+1) {
color: red;
}

This will select the 1st, 4th, 7th, etc., elements.

Every 2nd element (even elements):

li:nth-child(2n) {
color: blue;
}

This will select the 2nd, 4th, 6th, etc., elements.

Specific element (5th element):

li:nth-child(5) {
font-weight: bold;
}

This will select only the 5th element.

Examples:

Example 1: Styling Odd and Even List Items

<!DOCTYPE html>
<html>
<head>

  <style>
    li:nth-child(odd) {
      background-color: lightgray;
    }
    li:nth-child(even) {
      background-color: white;
    }
  </style>
</head>

<body>

  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
  </ul>

</body>
</html>

Output:

  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5
  • Item 6

Example 2: Highlighting Every 3rd Paragraph

<!DOCTYPE html>
<html>
<head>

  <style>
    p:nth-child(3n) {
      background-color: yellow;
    }
  </style>

</head>
<body>

  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
  <p>Paragraph 4</p>
  <p>Paragraph 5</p>
  <p>Paragraph 6</p>
  <p>Paragraph 7</p>
  <p>Paragraph 8</p>
  <p>Paragraph 9</p>

</body>
</html>

Output:

Paragraph 1

Paragraph 2

Paragraph 3

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8

Paragraph 9