Selecting the nth element matching a selector

Updated . 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.

Browser Support

https://caniuse.com/mdn-css_selectors_nth-last-child_of_syntax Show archive.org snapshot

  • Chrome/Edge 111+
  • Firefox 113+
  • Safari 9+

Finding the last child matching a selector

There is :nth-last-child() Show archive.org snapshot .

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