0
0
CssHow-ToBeginner · 3 min read

How to Use nth-child in CSS: Simple Guide with Examples

Use the :nth-child() CSS pseudo-class to select elements based on their position among siblings. Inside the parentheses, you can use a number, formula, or keyword to target specific children, like :nth-child(2) for the second child or :nth-child(odd) for all odd children.
📐

Syntax

The :nth-child() selector targets elements based on their order within a parent. The value inside the parentheses can be:

  • number: selects the element at that exact position (e.g., 3 for the third child)
  • keyword: odd or even to select all odd or even children
  • formula: an+b where a and b are integers, selecting elements matching the pattern (e.g., 2n+1 for odd children)
css
selector:nth-child(an+b) {
  /* styles */
}
💻

Example

This example colors the second list item red, all odd items lightblue, and every third item green.

css
ul li:nth-child(2) {
  color: red;
}
ul li:nth-child(odd) {
  background-color: lightblue;
}
ul li:nth-child(3n) {
  font-weight: bold;
  color: green;
}
Output
<ul><li style="background-color: lightblue;">Item 1</li><li style="color: red; background-color: lightblue;">Item 2</li><li style="font-weight: bold; color: green;">Item 3</li><li style="background-color: lightblue;">Item 4</li><li style="background-color: lightblue;">Item 5</li><li style="font-weight: bold; color: green;">Item 6</li></ul>
⚠️

Common Pitfalls

One common mistake is confusing :nth-child() with :nth-of-type(). :nth-child() counts all child elements regardless of type, so if you want to select the nth element of a specific type, use :nth-of-type().

Another pitfall is forgetting that an+b formulas start counting from 1, not 0.

css
/* Wrong: selects the 2nd child regardless of type */
ul li:nth-child(2) {
  color: red;
}

/* Right: selects the 2nd <li> element */
ul li:nth-of-type(2) {
  color: red;
}
📊

Quick Reference

SelectorDescription
:nth-child(3)Selects the 3rd child element
:nth-child(odd)Selects all odd-numbered children (1, 3, 5, ...)
:nth-child(even)Selects all even-numbered children (2, 4, 6, ...)
:nth-child(2n)Selects every 2nd child (2, 4, 6, ...)
:nth-child(3n+1)Selects every 3rd child starting at 1 (1, 4, 7, ...)

Key Takeaways

Use :nth-child() to style elements based on their position among siblings.
Inside :nth-child(), use numbers, keywords (odd/even), or formulas (an+b) to select children.
Remember :nth-child() counts all child elements, not just those of a specific type.
Use :nth-of-type() if you want to select the nth element of a specific tag type.
Counting starts at 1, so an+b formulas match children starting from the first.