Selecting the nth element matching a selector

Posted . Visible to the public.

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.

Dennis Schreiner
Last edit
Dennis Schreiner
License
Source code in this card is licensed under the MIT License.
Posted by Dennis Schreiner to makandra dev (2025-04-16 14:19)