The :nth-child
pseudo class is commonly used for targeting elements based on their position within a parent container, for example the third element in a list or every even-numbered item. However, :nth-child
can do more.
In
modern CSS specifications (Level 4)
Show archive.org snapshot
, there’s an additional feature that lets you use :nth-child
in combination
with a list of css selectors
Show archive.org snapshot
. This way, you can target the nth-child within a subset of siblings matching a selector. For example:
.container
.foo
span.my-selector
.bar
div.my-selector
.container > *:nth-child(1 of .my-selector)
color: red
Here, you specifically target the first element with the .my-selector
class among the children of .container
— regardless of the type of element.
Why Is It So Useful?
Because in the past, it was not possible to express such a selector with pure CSS! This is basically exactly the behavior you want from the :nth-of-type()
pseudo class, but do not get. With :nth-of-type()
you can only grab the nth element of a certain type/tag.