More control over :nth-child() selections with the of S syntax
it is possible to select Elements in the DOM by their index. Using the .
But, there’s more creative selections you can do, if you omit the A parameter. For example:
:nth-child(n+3): Select every child from the 3rd one up (3rd, 4th, 5th, and so on).:nth-child(-n+5): Select every child up to the 5th one (1st, 2nd, 3rd, 4th, 5th).
Combine a few of these :nth-child() selections and you can select ranges of elements:
:nth-child(n+3):nth-child(-n+5): Select every child from the 3rd one up to the 5th one (3rd, 4th, 5th).
Using :nth-last-child() you can do similar selections, but instead of starting to count from the start, you start counting from the end.
If you want to take it to the next level, you can use :nth-child() to .
is the ability to optionally pass a selector list into :nth-child() and :nth-last-child().
CSS :nth-child(An+B [of S]?)
:nth-last-child(An+B [of S]?)
:nth-child(An+B [of S]?)
:nth-last-child(An+B [of S]?)When of S is specified, the An+B logic is only applied onto elements that match the given selector list S. This essentially means that you can prefilter children before An+B does its thing.
Zebra-striping, revisited
A classic example where :nth-child() is used, is when creating a zebra-striped table. It’s a visual technique in which each table row alternates colors. Normally, this would be approached as follows:
tr:nth-child(even) {
background-color: lightgrey;
}While this works fine for static tables, it becomes problematic when you start to dynamically filter the table contents. When, for example, row two gets hidden, you’d end up with rows one and three visible, each with the same background color.
To fix this, we can leverage :nth-child(An+B [of S]?) by excluding the hidden rows from the An+B logic:
tr:nth-child(even of :not([hidden])) {
background-color: lightgrey;
}Pretty sweet, right?
Photo by
SOCIAL SHARE CARD GENERATOR