The CSS :nth-child() selector
The CSS :nth-child() pseudo-class selects elements by their position among their siblings. Use keywords like odd and even for zebra-striped rows, or an an+b formula like 3n (every third) or 3n+1 (the 1st, 4th, 7th…). It counts among all siblings, which sometimes surprises people.
Overview
:nth-child() picks elements based on where they sit among their siblings. The two keywords cover the common cases: :nth-child(odd) and :nth-child(even) are how you stripe table rows or lists for readability.
For anything more, it takes an an+b formula. :nth-child(3n) matches every third element; :nth-child(3n+1) matches the 1st, 4th, 7th and so on — useful for styling the start of each row in a grid. You can also pass a plain number, :nth-child(2), to target one specific position.
The thing to watch is that it counts among all the siblings, regardless of type. p:nth-child(2) means "an element that is a <p> and is the second child" — if the second child is not a paragraph, nothing matches. When you want to count only elements of a given type, reach for :nth-of-type() instead. Related shortcuts :first-child and :last-child handle the ends.
Syntax
/* zebra striping */
tr:nth-child(even) {
background: #f5f7fb;
}
/* every third item */
.grid > :nth-child(3n) { … }
Example
<style>
.rows div { padding: 10px 14px; font: 15px system-ui, sans-serif; }
.rows div:nth-child(odd) { background: #eef2ff; }
.rows div:nth-child(even) { background: #fff; }
</style>
<div class="rows">
<div>Row 1</div><div>Row 2</div><div>Row 3</div><div>Row 4</div>
</div>
Best practices
- Use
:nth-child(odd)/evenfor zebra-striped rows and lists to aid readability. - Use an
an+bformula like3n+1to target a repeating position, such as the first item of each row. - Remember it counts all siblings — switch to
:nth-of-type()when you mean "the nth element of this type". - For the ends, the simpler :first-child and :last-child are clearer.
Frequently asked questions
How do I style every other row in CSS?
tr:nth-child(even) (or odd) to stripe alternate rows for easier reading.What does nth-child(3n+1) mean?
3n alone matches the 3rd, 6th, 9th.Why is my nth-child not matching?
p:nth-child(2) needs the 2nd child to be a paragraph. Use :nth-of-type() to count by type.What is the difference between nth-child and nth-of-type?
:nth-child() counts position among all siblings; :nth-of-type() counts position among siblings of the same element type.