CSS :nth-child() Selector Tutorial

Introduction

The :nth-child() CSS selector is used to select elements based on their position in a group of siblings. This selector allows you to apply styles to elements that match a specific formula.

Syntax

The syntax for the :nth-child() selector is as follows:
:nth-child(formula) {
   /* styles */
}
In the formula, you can use keywords like even, odd, n, or specific numbers to target elements.

Examples

Example 1: Selecting Every Odd Element

div:nth-child(odd) {
   background-color: lightblue;
}
<div>First element</div>
  <div>Second element</div>
  <div>Third element</div>
  <div>Fourth element</div>
  
Result:
First element
Second element
Third element
Fourth element
In this example, the CSS rule will apply a light blue background color to every odd <div> element.

Example 2: Selecting Specific Elements

ul li:nth-child(3) {
   color: red;
}
  <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
      <li>Item 5</li>
</ul>
  
Result:
  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5
In this example, the CSS rule will apply a red color to the third <li> element inside the <ul> element.

Example 3: Using the 'n' Keyword

table tr td:nth-child(2n) {
   background-color: lightgreen;
}
<table>
    <tr>
     <td>1</td>
     <td>2</td>
     <td>3</td>
     <td>4</td>
     <td>5</td>
    </tr>
</table>
Result:
1 2 3 4 5
In this example, the CSS rule will apply a light green background color to every second <td> element in each row of the <table>.