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:

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:

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:

/* 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.