Change Grid Layout Using Quantity Queries

Explore different examples of changing grid layout using quantity queries.

The trick of using :nth-child in the previous hero example is known as a quantity query. First developed by Heydon Pickering way before :has() existed, quantity queries originally leveraged :nth-last-child as a bit of a hack to count and style precise numbers of elements.

Using :has(), we can style based on quantities of child elements in a few different ways:

  • ul:has(> :nth-child(2)) selects the ul if it has two or more children.

  • ul:has(> :nth-child(2):last-child) selects the ul if it has exactly two children.

Creating an adaptive image grid

With quantity queries in mind, let’s consider an image grid. Based on the number of items and whether there’s an odd or even number of them, we’ll update the styling accordingly:

  • The image aspect ratios

  • The number of columns and rows spanned by list items

  • The number of columns in the grid

The image below shows how our grid layout adapts to differing numbers of images.

Get hands-on with 1400+ tech skills courses.