CSS: nth-child arg of selector

By Xah Lee. Date: .

:nth-child(arg of selector)

:nth-child(arg of selector) is supported by browsers since 2024.

tag:nth-child(arg of selector)

match element x if:

  • tag matches x.
  • selector matches x
  • of all x's siblings, consider only those matched by selector, x is the argth.

tag is optional. It can be a simple selector (selecting by tag name, id, class etc) or a compound selector (combination of tag name, id, class etc). If empty, it means the universal selector (* any tag).

Think of it as filtering out children that does not match selector first, then applies tag:nth-child(arg) logic.

steps to match:

  1. Consider children of a parent.
  2. Consider only the children that matches selector.
  3. Of these children, consider if it is the nth. (or every argth of the normal nth-child parameter.)
  4. Consider it also match tag.

For example, if you have:

li:nth-child(2 of .x)

it means:

  1. look at all children of any element.
  2. it must have class x.
  3. of these children, is it the second?
  4. if so, is it also a list item li?

example. :nth-child(2 of .x)

here's a html.

<ul class="Mdp73">
<li class="x">dog 1</li>
<li class="a">dog 2</li>
<li class="x">dog 3</li>
</ul>

if we use this CSS:

.Mdp73 li:nth-child(2 of .x) {
 border: solid 1px grey;
}

browser shows:

it match the “dog 3”, because, of all children that are also class x, the “dog 3” is second.

example 2. contrast with .x:nth-child(2)

now if we use this css:

.p5Gx9 li.x:nth-child(2) {
 border: solid 1px grey;
}
and
<ul class="p5Gx9">
<li class="x">dog 1</li>
<li class="a">dog 2</li>
<li class="x">dog 3</li>
</ul>

browser shows:

no match. because, second child is the “dog 2”, but it does not have class x.

example 3.

now if we use

.YM6BQ li:nth-child(2 of .x) {
 border: solid 1px grey;
}

on

<ul class="YM6BQ">
<li class="x">dog 1</li>
<li class="x">dog 2</li>
<li class="x">dog 3</li>
</ul>

browser shows:

match “dog 2”, because of all children that also has class x, the second one one is “dog 2”, and it matches YM6BQ li

:nth-child(arg of selector) vs :nth-of-type(tag)

tag:nth-child(arg of selector) is similar to but more powerful than nth-of-type() selector , because we can filter by any class or compound selector not just tag name (aka type).

CSS selectors by child or sibling rank

CSS. Selectors

Selector types
Simple selectors
Combinators
Selector list
Nesting syntax
Special selector
Misc