On nth-child, mathematics, and that moment in school when your teacher said you'd use Algebra in real life

CSS's nth-child and nth-of-type are powerful, but recently I've seen them used improperly by mistakenly using the multiplier as the offset.

Recently, I’ve seen a recurring error with how :nth-child() and :nth-of-type() selectors are being used, so I wanted to host an anonymous algebra moment on these, my favorite CSS Level 3 selectors.

Frequently, I see :nth-child() selectors used for making columns:

Six Columns

From here, I see a lot of selectors like this:

Here’s why that is incorrect: the browser starts counting at 1 (the first item) and checks item each to see if that element matches the pattern (an+b) where “a” is the number you gave it, “n” is a set of all integers, and “b” is the offset that I’ve seen omitted (which defaults to zero). This is what happens:

Six columns with all N values

As you can see:

TL;DR: The important take-away here is that the repetition is the a in an+b. So a is the total number of columns in your layout, not the “column number” you’re trying to address. The column number is the “+b”, The Offset!

What you want is this:

With correct N values

And this stacks vertically as expected:

Three columns, multiple rows

But the way I had it (usually) worked! What’s wrong with that? Two reasons: it doesn’t always work, and pride. ;-)

Look at it this way:

Three columns, bad N values

Why am I pestering you with this?

Does it matter if only one row is used in the layout?

Yes. That :nth-child(1n) selects every column and the :nth-child(2n) selects every even column, overriding the first rule. That’s inefficient and makes debugging and careful overrides that much harder.

And what about :nth-child() vs. :nth-of-type()?

Additional Resources