How Does the CSS nth-child Formula Work?
The CSS :nth-child() pseudo-class targets elements based
on their index position among a group of siblings using the functional
algebraic formula an + b. This article breaks down how
variables a and b operate, demonstrates how
the browser evaluates cycle intervals and offsets, and provides
practical examples for creating zebra striping, recurring intervals, and
custom element patterns without modifying markup.
The Core Math: Understanding
an + b
At its simplest, :nth-child() uses the linear equation
an + b where:
a(Cycle / Step): An integer that represents the size of the recurring pattern cycle.n(Counter): A non-negative integer counter that starts at0and increments by1(0, 1, 2, 3, ...).b(Offset): An integer that shifts the starting position of the selection.
The browser evaluates the equation for all non-negative integers of
n, but it only selects elements with resulting matching
indexes greater than or equal to 1, since CSS uses 1-based
sibling indexing.
How the Browser Computes the Formula
To see the formula in action, consider
li:nth-child(3n + 1) applied to an unordered list:
- For
n = 0:(3 * 0) + 1 = 1(Targets the 1st item) - For
n = 1:(3 * 1) + 1 = 4(Targets the 4th item) - For
n = 2:(3 * 2) + 1 = 7(Targets the 7th item) - For
n = 3:(3 * 3) + 1 = 10(Targets the 10th item)
The selector effectively targets every third element starting at index 1.
Alternating Elements with Keywords and Formulas
For alternating patterns like zebra-striped table rows, CSS provides
built-in keywords that map directly to the an + b
formula:
odd/2n + 1: Matches items1, 3, 5, 7, 9, ...even/2n(or2n + 0): Matches items2, 4, 6, 8, 10, ...
/* Alternating background rows using keywords */
tr:nth-child(even) {
background-color: #f2f2f2;
}
/* Equivalent pattern using the formula */
tr:nth-child(2n) {
background-color: #f2f2f2;
}Pattern Variations and Offset Techniques
Manipulating a and b allows for complex UI
grid and list layouts.
Selecting the First N Elements
Using a negative multiplier (-n + b) limits the
selection to the first group of elements up to index b.
/* Selects the first 4 elements (indexes 4, 3, 2, 1) */
li:nth-child(-n + 4) {
font-weight: bold;
}Selecting All Elements After a Specific Index
Setting a to 1 (or simply n)
with an offset selects every element starting from that point
onwards.
/* Selects every element from the 5th item onward */
li:nth-child(n + 5) {
opacity: 0.7;
}Complex Recurring Grid Patterns
For multi-column layouts, combining step and offset properties allows
targeting specific columns. For instance, in a 4-column card grid,
targeting the last item of each row uses 4n:
/* Targets columns 4, 8, 12, etc. */
.card:nth-child(4n) {
margin-right: 0;
}By mastering the calculation rules of an + b, you can
structure responsive layouts, clean tabular data, and dynamic recurring
designs entirely through stylesheets.