Sub topic 6
Counting with :nth-child() and An+B
This chapter covers how :nth-child() counts elements and how to write the An+B expressions it accepts. It assumes you can write CSS rules with type, class, and attribute selectors, and that you know the descendant and child combinators. It also assumes you have seen :first-child and :last-child, which the previous chapter covered.
What :nth-child() does
:nth-child() is a structural pseudo-class. It matches an element based on its position among all of its siblings, counting from 1. Position is not about the element's type or class. Every element child of the same parent gets a number, and the selector matches the ones whose number fits the expression you give it.
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>li:nth-child(2) {
color: #c00;
}This rule matches "Two", because it is the second child of the ul. The counter starts at 1, not 0. Text nodes and comments are not counted, only elements.
Two keywords cover the most common cases:
:nth-child(odd)matches positions 1, 3, 5, and so on.:nth-child(even)matches positions 2, 4, 6, and so on.
The zebra-stripe rule from the chapter examples uses the second keyword:
tr:nth-child(even) {
background: #f5f5f5;
}The An+B formula
For anything beyond a single position, :nth-child() takes an expression of the form An+B.
Ais the step size, the number of positions between matches.nis a counter that the browser runs through 0, 1, 2, 3, and so on.Bis the offset, the position where counting starts.
The browser plugs in each value of n, computes A*n + B, and matches the element at that position if the result is a positive whole number that exists. Results of zero or below match nothing.
| Expression | Values computed (n = 0, 1, 2, ...) | Matches positions |
|---|---|---|
| `2n` | 0, 2, 4, 6 | 2, 4, 6, ... (same as even) |
| `2n+1` | 1, 3, 5, 7 | 1, 3, 5, ... (same as odd) |
| `3n` | 0, 3, 6, 9 | 3, 6, 9, ... |
| `3n+1` | 1, 4, 7, 10 | 1, 4, 7, ... |
| `n+3` | 3, 4, 5, 6 | 3 and every later position |
| `-n+3` | 3, 2, 1, 0, -1 | 1, 2, 3 only |
| `5` | 5 | Position 5 only |
Walk through 3n+1 once to see the process. With n = 0 the result is 1. With n = 1 it is 4, with n = 2 it is 7. So every third element matches, starting with the first.
Reading the shapes
You will use only a few shapes in practice:
- A fixed number, such as
:nth-child(5). It matches one position. There is non. - Every Nth item, such as
:nth-child(4n). Use4n+1instead if the first item of each group should match. - From position B onward, such as
:nth-child(n+4). BecauseAis 1, it matches position 4 and everything after it. - The first B items, such as
:nth-child(-n+3). With a negativeA, the values shrink asngrows, so the selector matches only up to positionB. - A range, made by combining shapes 3 and 4 (shown below).
The chapter's earlier example uses the fourth shape to make the first three list items bold:
li:nth-child(-n + 3) {
font-weight: bold;
}Whitespace around the + or - that joins An and B is allowed, so -n + 3 and -n+3 are the same. Spaces inside a term are not allowed. The + or - must be a separate token from the digits, so write 2n + 1 or 2n+1, but not 2 n+1.
Selecting a range
To select positions 3 through 6, you need two conditions at once: "position 3 or later" and "position 6 or earlier". Chain two :nth-child() selectors on the same element:
li:nth-child(n + 3):nth-child(-n + 6) {
background: #fff3c4;
}Both pseudo-classes must be true for the element to match. The first excludes positions 1 and 2. The second excludes positions 7 and later. What remains is 3, 4, 5, and 6.
Counting from the end
:nth-last-child() uses the same An+B syntax but counts from the last sibling backward. :nth-last-child(1) is the same as :last-child, and :nth-last-child(2) is the second item from the end.
Counting from the end is useful when you do not know how many items there are. This rule styles the last three items, however many exist:
li:nth-last-child(-n + 3) {
border-bottom: 2px solid #1a73e8;
}You can combine both directions to detect a count. If an item is the third from the start and also the third from the end, the list has exactly five items.
li:nth-child(1):nth-last-child(3),
li:nth-child(1):nth-last-child(3) ~ li {
width: 33.333%;
}The first part matches the first item only when it is also third from the end, which means the list has exactly three items. The second part matches every sibling after it. Together they style every item in a three-item list and no item in lists of other lengths. This is a known technique ("quantity queries"), though today :has() or container-based layout is often simpler.
Filtering with `of S`
:nth-child() accepts an optional of clause with a selector list. The count then runs only over siblings that match the selector, though the element being tested must also match it.
li:nth-child(odd of .visible) {
background: #f0f6ff;
}Suppose some items have class="visible" and others are hidden by being filtered out with a different class. The count ignores items without .visible. The first visible item is position 1, the second is position 2, and so on. This fixes a classic problem: zebra striping that breaks when some rows are hidden with display: none, since hidden elements still count as children in the plain form.
Check browser support for of S before relying on it. It is available in current versions of all major browsers, but older ones ignore the whole rule if they do not recognize it.
Common errors
Expecting :nth-child() to count only one type. In p:nth-child(2), the second child of the parent must be a p. If the second child is a div, nothing matches, even when the second p exists. The count includes every element sibling, and the type selector only acts as an extra condition. The next chapter covers :nth-of-type(), which counts per type.
<section>
<h2>Title</h2>
<p>First paragraph</p>
<p>Second paragraph</p>
</section>p:nth-child(2) {
color: #c00;
}This colors "First paragraph", since the h2 is child 1 and the first p is child 2. "Second paragraph" is child 3 and does not match.
Starting at zero. :nth-child(0) matches nothing because positions start at 1. The expression 0n+3 is valid, but it is just a roundabout way to write 3.
Confusing n+3 with 3n. n+3 means "position 3 and everything after it". 3n means "every third item". They look similar but produce very different results.
Writing a negative result and expecting a match. -n+3 matches positions 1 to 3 because n runs 0, 1, 2, 3, and results of 0 or less are dropped. People sometimes write -3n expecting "the first three", which matches nothing.
Leaving out the type or class. A bare :nth-child(even) matches every even child anywhere in the document. Scope it, for example .results > li:nth-child(even), so it applies only where you intend.
Specificity surprises. A pseudo-class adds the same weight as a class selector. So li:nth-child(2) outranks li.plain? No: both have one class-level part plus one type part, so they tie, and the later rule in the source wins. The of S clause also adds the specificity of the selectors inside it.
How the count is evaluated
The browser decides a match per element, not per rule. For each candidate element it finds the element's index among its siblings and checks whether some non-negative integer n makes An+B equal that index.
For position 7, n = 2 gives 3*2 + 1 = 7, so it matches. For position 6, no whole n works, so it does not.
Putting it together
A common layout need is a card grid where the last item in every row of three has no right margin:
.cards > .card {
margin-right: 1rem;
}
.cards > .card:nth-child(3n) {
margin-right: 0;
}Every third card (3, 6, 9, ...) ends a row, so it drops its margin. This relies on exactly three cards per row, so it breaks if the grid reflows to a different column count. For responsive grids, gap on a grid or flex container is more reliable. Use :nth-child() when the structure is fixed, such as table rows, short lists, or fixed pattern designs.
Exercise
A list has 10 li items. Which positions does li:nth-child(n + 4):nth-child(-n + 7) match, and which single An+B expression would match every second item starting at position 2 (2, 4, 6, 8, 10)?
Show answer
The first selector matches positions 4, 5, 6, and 7. n + 4 excludes positions 1 to 3, and -n + 7 excludes positions 8 to 10. Every second item starting at position 2 is 2n (or the keyword even).
Exercise
A section contains an h2, then two p elements. Does p:nth-child(2) match the second paragraph? Explain.
Show answer
No. It matches the first paragraph. :nth-child() counts all element siblings, so the h2 is child 1, the first p is child 2, and the second p is child 3. The type selector only adds a condition that the matched element is a p.
Exercise
Write a selector that bolds the last two items of any ul list, regardless of its length.
Show answer
ul > li:nth-last-child(-n + 2) { font-weight: bold; } The expression -n + 2 matches positions 1 and 2 counted from the end.