WebCraft

:has(:nth-child())

A layout that changes when the list gets long

  • item 1
  • item 2
  • item 3

CaveatA quantity query counts children, so it re-runs whenever the list changes. Keep the threshold to one breakpoint: chaining several counts makes the layout jump twice while items are still loading in.

FallbackYou cannot nest :has() inside :has(), and it will not match pseudo-elements. Both are silent failures — the rule is simply dropped.

CSS
/* four or more, go two across */
.list:has(li:nth-child(4)) {
  grid-template-columns: 1fr 1fr;
}

Published

Questions

<details name>

Can CSS count how many items are in a list?

Effectively yes — :has(> :nth-child(n)) asks whether an nth child exists, which is a count in everything but name. The layout can switch from a row to a grid at a threshold with no JavaScript watching the list.

Why does my quantity query flicker while the page loads?

Because it re-runs every time the list changes, so items arriving one at a time cross the threshold as they land. Keep it to a single threshold; chaining several counts makes the layout jump twice before the data has finished arriving.

What can :has() not do here?

It cannot be nested inside another :has(), and it will not match pseudo-elements. Both fail silently — the rule is simply dropped, with nothing in the console to say why.