nth-child pseudo-class --Introduction to CSS [CSS3 compatible]

The nth-child pseudo-class is a pseudo-class for setting the style by specifying the position of a specific sibling from the perspective of the parent. Often used in combination with the li tag.

Apply style only to even numbers

To apply the style only to even numbers, use ": nth-child (2n)". Specifies the case where the sibling position is a multiple of 2.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
<style>
  .my_list1 li: nth-child (2n) {
    background: #ddd;
  }
</style>

<div class = "my_list1">
  <ul>
    <li> 1 </li>
    <li> 2 </li>
    <li> 3 </li>
    <li> 4 </li>
    <li> 5 </li>
    <li> 6 </li>
  </ul>
</div>

Apply style only to odd numbers

To apply the style only to odd numbers, use ": nth-child (2n + 1)". Specifies the case where the sibling position is "multiple of 2 + 1".

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
<style>
  .my_list2 li: nth-child (2n + 1) {
    background: #ddd;
  }
</style>

<div class = "my_list2">
  <ul>
    <li> 1 </li>
    <li> 2 </li>
    <li> 3 </li>
    <li> 4 </li>
    <li> 5 </li>
    <li> 6 </li>
  </ul>
</div>

Details of nth-child pseudo-class

: nth-child () pseudo-class --MDN web docs

Associated Information