9.10 · Layout

Layout by item count: quantity queries

Change a layout based on how many items it holds, with :has() and :nth-child().

.grid:has(> :nth-child(5)) reads as “a grid that has a fifth child”, which means five or more items. Combined with :last-child, it can match an exact count: :nth-child(3):last-child means exactly three.

A gallery can show one large image, two side by side, a feature layout for three and a dense grid for many, without counting items in JavaScript or setting classes in a template.

Before
<!-- Set by the template -->
<div class="grid grid--count-3">
/* or JS */
grid.dataset.count = grid.children.length
Now
.grid:has(> :nth-child(2)) {
  grid-template-columns: 1fr 1fr;
}
.grid:has(> :nth-child(3):last-child)
  > :first-child { grid-row: span 2; }
.grid:has(> :nth-child(5)) {
  grid-template-columns: repeat(3, 1fr);
}