CSS Reference ยท Pseudo-classes
The :nth-child() pseudo-class
Reference for the CSS :nth-child() pseudo-class: select elements by position with odd, even and an+b formulas, plus the of S filter, with live examples.
The :nth-child() pseudo-class matches an element by its position among all of its siblings, counting from 1. You give it a keyword (odd, even), a plain number, or a formula of the form an+b. It is the tool behind zebra-striped rows, "every third card" layouts and "the first three items" rules.
Optionally you can add of S and a selector list. The position is then counted only among siblings that match that list.
li:nth-child(2n + 1) { background: #f1f5f9; }
Try it
Syntax
:nth-child( <nth> [ of <selector-list> ]? ) { } /* <nth> is one of: */ /* odd | even | <integer> | <an+b> */
- Specificity: the pseudo-class itself adds (0, 1, 0). With
of S, it also adds the specificity of the most specific selector inS. - Counting: starts at 1. The formula is evaluated for n = 0, 1, 2, 3 ... and every result that is a valid position (1 or more) matches.
Values
| Syntax and arguments | Description |
|---|---|
odd |
Positions 1, 3, 5 ... Same as 2n+1. |
even |
Positions 2, 4, 6 ... Same as 2n. |
3 |
Exactly the third child. |
3n |
Every third child: 3, 6, 9 ... |
3n + 1 |
Positions 1, 4, 7 ... |
n + 4 |
The fourth child and all that follow. |
-n + 3 |
The first three children (3, 2, 1). |
-n + 5 plus n + 2 |
Chain :nth-child(-n + 5):nth-child(n + 2) to select a range, here positions 2 to 5. |
of S |
Counts only siblings matching the selector list S, for example :nth-child(2 of .visible). |
Usage notes
- Position counts every sibling. In
p:nth-child(2), the second child must be a<p>. If the second child is an<h2>, nothing matches. Use:nth-of-type()to count only one tag. - Use
of Sto skip hidden or filtered items.li:nth-child(odd of :not(.hidden))stripes only the visible rows, even when some rows are hidden with a class. - Spaces around
+and-are required. Write2n + 1;2n+1is also fine, but2n +1is invalid. - A negative step counts the other way.
-n + 3has results 3, 2, 1, so it selects the first three. - Insertion changes everything. Adding an element at the top shifts every position, which is usually exactly what you want for striping.
- Do not use it for meaning. Styling by position is presentational. If an item is special for a reason, give it a class.
Browser support
The basic an+b forms work in every browser. The of S argument is Baseline since 2023 (Chrome and Edge 111, Firefox 113, Safari 9).
Related
:nth-last-child()โ the same, counted from the end:nth-of-type()โ position among siblings of one tag:first-childand:last-child- Lesson: Structural Pseudo-classes
- Lesson: Selector Functions