Explore the An+B CSS Microsyntax for :nth-child()
Result
Explanation
Think of a simple list of numbers from 0 to infinity. The one from primary school. 0, 1, 2, 3, and so on.
Now plug these numbers one after the other into the An+B formula in the place of the variable n and calculate the result, again just like in primary school. Example:
3 × 0 + 2 = 2 3 × 1 + 2 = 5 3 × 2 + 2 = 8 3 × 3 + 2 = 11 ...
You get a new list of numbers. These might not start from 0 or 1, they might have gaps or they might even be partially negative. Go through the list one by one. Each list item corresponds now to a matching HTML element to be selected.
Negative list items are ignored. HTML elements not on the list are not selected. HTML elements start counting from 1.
If the whole new list is negative or 0, then no HTML element will be selected at all.
Common Examples
- Every even item
:nth-child(2n)
- Every odd item
:nth-child(2n + 1)
- Every fifth item, starting with the first
:nth-child(5n + 1)
- Every fifth and sixth item
:where(:nth-child(5n), :nth-child(6n))
We use the:where()
selector here to select two ranges at the same time. Note that this is different from selecting the fifth and the following. This here will have a slightly chaotic pattern. E.g., the item no. 30 will match both being a fifth and a sixth.- OK, how do I select every fifth and the next?
:where(:nth-child(5n), :nth-child(5n + 1))
Basically the same trick as above, but we slightly changed the second selector in the:where()
.- The first 4 items
:nth-child(-1n + 4)
- The last 3 items
:nth-last-child(-1n + 3)
Attention! We’re cheating here. It is not reliably possible with:nth-child()
to select from the end (unless you already know the exact number of elements). For this requirement we therefore use:nth-last-child()
.- I’ve got an off-by-one error!
- The
:nth-child
and:nth-last-child
pseudo-classes select based on the actual DOM nodes in the document. That means, every stray<script>
,<li hidden>
and so on is taken into account, too, even if it is not visible. Check in the inspector tab of your browser’s developer tools for such an element. In some cases you can work around the problem with the:nth-of-type
pseudo-class. - Every even non-hidden item
- Manuel Matuzović mentioned
the
of S
syntax, which allows to select based on a further selector. Usually:nth-child()
selects under all children of an element (hence the name). To select only from elements without, e.g., thehidden
attribute, one can use
:nth-child(even of :not([hidden]))