Sub topic 8
Styling by number of children
You can write CSS that reacts to how many children an element has by combining :has() with :nth-child(). This chapter covers how that works, the patterns for "at least", "at most", and "exactly" N children, and the points where these selectors go wrong.
This chapter assumes you know how :nth-child() and the child combinator > work. It also assumes you can read the :has() syntax from earlier chapters and calculate selector specificity at a basic level.
The idea: a fourth child proves there are four
CSS has no "count" operator. You can test whether a child exists at a certain position, though, and that is enough.
The selector :nth-child(4) matches an element only if it is the fourth element among its siblings. If a fourth child exists, the parent has at least four children. Wrapping that test in :has() moves the match from the child up to the parent:
ul:has(> li:nth-child(4)) {
columns: 2;
}This rule matches a ul that has at least four direct li children. Selectors that style an element based on how many children it has are called quantity queries. Before :has(), you could only write them with a trick that styled the children themselves. The parent was out of reach.
Counting only some children
:nth-child(4) counts every element sibling, whatever its type. In :has(> li:nth-child(4)), the li must be the fourth element child of the parent. Consider this markup:
<ul class="menu">
<li class="title">Menu</li>
<li><a href="/a">A</a></li>
<li><a href="/b">B</a></li>
</ul>Here .menu:has(> li:nth-child(4)) does not match, because only three children exist. If you want to count only items of one kind, use the of S syntax, which counts only siblings that match a selector:
.menu:has(> :nth-child(4 of li:not(.title))) {
columns: 2;
}This matches when there are at least four li children that are not titles. The of S syntax is supported in current Chrome, Firefox, and Safari, but check your support targets before relying on it. A simpler option is :nth-of-type(), which counts only siblings with the same tag name.
Two details affect counts:
- Text nodes are not elements, so they are never counted.
- Elements with
display: nonestill count, because selectors work on the DOM and not on what is rendered.
At least, at most, and exactly
The basic form gives you "at least N". The other two comparisons need :not() or a different technique.
At most N
"At most 3" means "not at least 4". Negate the test:
ul:not(:has(> li:nth-child(4))) {
display: flex;
gap: 1rem;
}This matches lists with three or fewer li children, including empty lists. The :not() wraps the whole :has() selector, so it is the list that is being negated, not the child.
Exactly N
"Exactly 3" means "at least 3 and not at least 4". Chain the two conditions:
ul:has(> li:nth-child(3)):not(:has(> li:nth-child(4))) {
grid-template-columns: repeat(3, 1fr);
}There is a shorter way that uses only one :has(). The first child is the only element whose position from the end equals the total child count. So if the first child is also the third from the end, the parent has exactly three children:
ul:has(> li:first-child:nth-last-child(3)) {
grid-template-columns: repeat(3, 1fr);
}This is the classic quantity query technique, now applied to the parent. It uses :nth-last-child() with the an+b forms that you already know, so you can express ranges too.
| Condition | Selector |
|---|---|
| Exactly 3 children | `ul:has(> li:first-child:nth-last-child(3))` |
| At least 4 children | `ul:has(> li:nth-child(4))` |
| At most 4 children | `ul:has(> li:first-child:nth-last-child(-n+4))` |
| Between 2 and 4 children | `ul:has(> li:first-child:nth-last-child(n+2):nth-last-child(-n+4))` |
| Exactly 1 child | `ul:has(> li:only-child)` |
| No `li` children | `ul:not(:has(> li))` |
In the "between" row, the two nth-last-child conditions apply to the same element. The first child must sit between the second-from-last and fourth-from-last positions, which is only true when the list has 2 to 4 items.
A worked example: a responsive gallery
This example adjusts a gallery's column count to the number of figures in it. It runs as written when you place it in an HTML page.
<div class="gallery">
<figure>One</figure>
<figure>Two</figure>
<figure>Three</figure>
<figure>Four</figure>
</div>.gallery {
display: grid;
gap: 0.5rem;
grid-template-columns: 1fr;
}
.gallery:has(> :nth-child(2)) {
grid-template-columns: repeat(2, 1fr);
}
.gallery:has(> :nth-child(5)) {
grid-template-columns: repeat(3, 1fr);
}
.gallery figure {
margin: 0;
padding: 1rem;
background: #eef;
}The three rules have different meanings:
- With one figure, no rule matches and the gallery stays at one column.
- With two to four figures, the second rule matches, so the grid has two columns.
- With five or more figures, both the second and third rules match. They have the same specificity, so the later rule wins and the grid has three columns.
This pattern works because each "at least" rule is cumulative and the cascade resolves the overlap. Order the rules from the smallest threshold to the largest. If you reverse the order, the smaller threshold overrides the larger one and the three-column layout never applies.
The rules also keep working when the page changes. If JavaScript appends a fifth figure, the browser re-evaluates the selectors and the layout switches to three columns. You do not need to write any code to count items.
Showing an empty state
Quantity queries also cover the zero case. A common use is an "empty" message that appears only when a results list has no items:
<section class="panel">
<ul class="results"></ul>
<p class="empty">No results found.</p>
</section>.empty {
display: none;
}
.panel:not(:has(.results > li)) .empty {
display: block;
}The message is visible only when the panel contains no li inside .results. When a script adds an item, the message hides itself. Note that :empty is not a substitute here. It fails if the element contains even a whitespace text node, while :not(:has(> li)) ignores text and tests only for elements.
Specificity of quantity queries
Recall from the earlier chapter that :has() takes the specificity of its most specific argument. The same applies to :not(). For the selector ul:has(> li:nth-child(4)):
ulcontributes (0,0,1).- The argument
> li:nth-child(4)contributes a type selector (0,0,1) and a pseudo-class (0,1,0), so (0,1,1). - The total is (0,1,2).
That is higher than a plain class selector such as .list, which is (0,1,0). A quantity rule can therefore override a class rule that you expected to win. If the base rule uses .list and the quantity rule uses ul:has(> li:nth-child(4)), the quantity rule wins even if it comes first. Use :where() around the part you want to neutralize if this causes trouble. For example, :where(ul):has(> :nth-child(4)) removes the type selector's weight.
Common mistakes
- Forgetting
>.ul:has(li:nth-child(4))matches aulcontaining anylithat is the fourth child of its own parent. With nested lists, a nestedliat position four makes the outer list match. Use>to count direct children only. - Counting from the wrong end.
:nth-child()counts from the start.:nth-last-child()counts from the end. Mixing them up flips your "at most" and "at least" logic. - Using
:has(:nth-child(4))with no>. Any descendant at any depth counts, which is rarely what you intend. - Assuming visible items are counted. Hidden elements count. If you filter a list by hiding items, a quantity query still sees all of them.
Performance and limits
A quantity query has to check the children of each candidate parent whenever the DOM changes inside it. For a small list this is cheap. For a list with thousands of items, a broad selector like :has(:nth-child(4)) forces the browser to look at every descendant. Keep the subject specific (ul.menu, not *) and use > so the search stops at direct children.
CSS cannot do arithmetic on the count, so you cannot set a column count equal to the number of items. You can only pick between a finite set of layouts. If you need to know the exact number for a calculation, set a custom property from JavaScript.
Exercise
Write a selector for a div.toolbar that matches only when it has exactly two direct children, regardless of their tag names.
Show answer
div.toolbar:has(> :first-child:nth-last-child(2)). The first child is also the second from the end only when the parent has exactly two children.
Exercise
A page has .list:has(> li:nth-child(3)) { gap: 2rem; } followed by .list:has(> li:nth-child(6)) { gap: 1rem; }. What gap does a list with seven items get, and why? What happens if you swap the two rules?
Show answer
Seven items match both rules. They have equal specificity (0,2,1), so the later rule wins and the gap is 1rem. After swapping, the later rule is the three-item rule, so the gap becomes 2rem for every list with three or more items, and the six-item rule never takes effect.
Exercise
Why does ul:has(li:nth-child(4)) sometimes match a list with only two direct children?
Show answer
Without >, the argument matches any descendant li. A nested list inside one of the two items can contain a fourth child, which makes the outer ul match.