How to Select nth Child in CSS: Simple Guide with Examples
Use the
:nth-child(n) pseudo-class in CSS to select the nth child element of its parent. Replace n with a number, formula, or keyword to target specific children, like :nth-child(3) for the third child or :nth-child(2n) for every even child.Syntax
The :nth-child() selector targets elements based on their position among siblings. The n inside can be a number, a formula like 2n, or keywords like odd or even.
:nth-child(3)selects the third child.:nth-child(2n)selects every even child (2nd, 4th, 6th, ...).:nth-child(2n+1)selects every odd child (1st, 3rd, 5th, ...).
css
selector:nth-child(n) {
/* styles here */
}Example
This example colors the third list item red and every even list item blue.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>nth-child Example</title> <style> ul li:nth-child(3) { color: red; font-weight: bold; } ul li:nth-child(even) { color: blue; } </style> </head> <body> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> </ul> </body> </html>
Output
A list of 5 items where the 3rd item is red and bold, and the 2nd and 4th items are blue.
Common Pitfalls
One common mistake is confusing :nth-child() with :nth-of-type(). :nth-child() counts all element types, while :nth-of-type() counts only siblings of the same type.
Also, remember n starts counting at 1, not 0.
css
/* Wrong: expecting to select 2nd <li> but parent has other elements */ ul li:nth-child(2) { color: green; } /* Right: use nth-of-type to select 2nd <li> ignoring other elements */ ul li:nth-of-type(2) { color: green; }
Quick Reference
| Selector | What it selects |
|---|---|
| :nth-child(1) | First child element |
| :nth-child(odd) | All odd-numbered children (1, 3, 5, ...) |
| :nth-child(even) | All even-numbered children (2, 4, 6, ...) |
| :nth-child(3n) | Every 3rd child (3, 6, 9, ...) |
| :nth-child(2n+1) | All odd children (same as odd) |
| :nth-child(4n+2) | Every 4th child starting at 2 (2, 6, 10, ...) |
Key Takeaways
Use :nth-child(n) to select elements by their position among siblings.
The argument n can be a number, formula, or keywords like odd/even.
:nth-child() counts all element types, so use :nth-of-type() if you want to count only specific element types.
Counting starts at 1, not 0.
Common formulas include 2n (even), 2n+1 (odd), and n for every element.