nth-child()

Nth-child() targets elements based on their position within a specific parent element. It offers precise control over styling elements based on their order.

Syntax

selector:nth-child(n) {
  /* Styles to apply */
}

selector: The parent element containing the elements you want to target.

n: The formula used to specify which children to match:

  • Specific index: n is a positive integer representing the child’s position (e.g., nth-child(2) targets the second child).
  • Even/odd: n is one of these keywords:
    • even (matches even-numbered children)
    • odd (matches odd-numbered children)
  • Formula: n is a formula using arithmetic operators (+, -, *, /) and keywords like 2n, 3n, 4n+1, etc.

Examples

  • Target the second child
.parent-element:nth-child(2) {
  color: blue;
}
  • Target even-numbered children
.parent-element:nth-child(even) {
  background-color: #f0f0f0;
}
  • Target every third child
.parent-element:nth-child(3n) {
  font-weight: bold;
}
  • Target children starting from the fourth, every other child
.parent-element:nth-child(4n+1) {
  border: 1px solid #ccc;
}

Key Points

  • nth-child starts counting from 1, not 0.
  • The formula n can be complex to understand, but it offers great flexibility.
  • You can combine nth-child with other selectors for more specific targeting.
  • If you need to target elements based on their type or class, consider using :nth-of-type or :nth-of-a-kind.