:nth-child(n)

The :nth-child(n) CSS pseudo-class is used to select elements based on their position within a specific parent element. The n part is a formula that determines which child elements to select.

Basic Usage

/* Selects the second child of every parent element */
p:nth-child(2) {
  color: blue;
}

/* Selects the first, third, fifth, etc. child of every parent element */
div:nth-child(odd) {
  background-color: lightgray;
}

/* Selects the second, fourth, sixth, etc. child of every parent element */
li:nth-child(even) {
  font-weight: bold;
}

Formula-Based Selection

You can use more complex formulas within the parentheses to select specific children:

/* Selects the third child of every parent element */
p:nth-child(3) {
  font-style: italic;
}

/* Selects every third child of every parent element */
li:nth-child(3n) {
  border: 1px solid red;
}

/* Selects the first, fourth, seventh, etc. child of every parent element */
div:nth-child(4n-3) {
  background-color: yellow;
}

Key Points

  • n: A variable that can represent any integer.
  • odd: Selects elements with odd indices (1, 3, 5, …).
  • even: Selects elements with even indices (2, 4, 6, …).
  • Formulas: Allow for more precise selection based on arithmetic operations.

Practical Example

Suppose you have an unordered list:

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

To style every other list item, you can use:

li:nth-child(even) {
  background-color: lightgray;
}

This will style the second, fourth, and fifth list items.