29 May 2023

:nth-child()

The :nth-child() is a pseudo-class that matches elements based on their position in a group of siblings.

Example

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>
li:nth-child(2) {
  color: grey;
}

Result

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

Other Examples

# select odd elements
:nth-child(odd)

# select even elements
:nth-child(even)

# select every 5th element
:nth-child(5n)