LIL DOLLY DESIGNS

Notes  ·  8 February 2025

First container queries

I have been waiting for these since 2018. They have been in stable browsers for two years. Here is what changed.

#css#web

I have been waiting for container queries since around 2018. They landed in stable browsers two years ago. I have used them in production for about a year. This is what changed in my work.

A short refresher, in case you have been avoiding the spec. A container query lets a component respond to the size of its parent, rather than to the size of the viewport. A media query says “if the screen is at least 700 pixels wide, do this”. A container query says “if my parent is at least 400 pixels wide, do this”. The component becomes aware of where it has been placed, and adjusts.

The thing this changes, in practice, is that components stop being responsible for knowing about pages. A card component used to need to know whether it was being used in a sidebar (narrow) or in a feature row (wide), and have media queries that more or less guessed. With container queries, the card knows the size of its container, and decides accordingly. Pages can put cards anywhere without breaking them. Cards can be moved between pages without rewriting their CSS.

The CSS itself is not complicated. Two declarations:

.card-container {
  container-type: inline-size;
  container-name: card;
}

@container card (min-width: 400px) {
  .card { display: grid; grid-template-columns: 1fr 2fr; }
}

That’s it. There is some subtlety around when to use inline-size versus size, and about naming versus unnamed containers, but the patterns settle quickly.

Ahmad Shadeed wrote the most useful single piece on container queries when they were still settling. Una Kravets has the second-most-useful. MDN has caught up since.

Two things I did not expect.

It changed how I write components, not just how I respond to layout. Components are now smaller, more self-contained, and easier to extract into a reusable library, because they no longer carry a list of “where I am allowed to be used”.

It changed how I write Figma. Or rather, it made it easier to stop pretending Figma was a layout tool. Figma describes appearance at fixed widths. Container queries describe behaviour. The two have always been at odds and now I am less troubled when the design file does not exactly match the implementation, because the implementation is doing something the file cannot really represent.

If you are not using container queries yet, the next time you find yourself writing a media query for a component, try a container query instead. Most of the time it will be the right tool.