Front-end2 min read

Container queries: a component that knows how much room it has

Media queries ask about the screen, container queries ask about the parent. We build a card that looks right in a sidebar and at full width.

container-queries

Illustrative photo: Unsplash

The same article card ends up on the home page, in a narrow sidebar and in a three-column grid. Media queries cannot help: the screen is equally wide everywhere, only the space the component gets changes. That is exactly what container queries are for — and they have worked in every modern browser since 2023.

Two steps: the container and the query

First we say which element is the container. inline-size means we care about width (and the browser does not have to measure height, which would be expensive).

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

Then we write styles that depend on the width of that container, not the window.

.card { display: grid; gap: 12px; }

@container card (min-width: 520px) {
  .card {
    grid-template-columns: 220px 1fr;
    align-items: start;
  }
}

Put the card in a 300 px column and it stacks vertically. Put it in 800 px of content and the image moves next to the text. Not a single line of JavaScript and no card--horizontal modifier classes.

Container-relative units

Along with the queries came new units: cqi is 1% of the container’s width. They are great for type that should grow with the component rather than with the whole screen.

.card h3 {
  font-size: clamp(1.1rem, 4cqi, 1.8rem);
}

Things to watch

  • An element cannot query itself — the query refers to the nearest container ancestor. That is why you need a wrapper.
  • container-type: size needs a known height; in 95% of cases inline-size is enough.
  • Name your containers. Without a name the query hits the nearest container, which is not always the one you think.

Rule of thumb Keep media queries for page layout (header, grid, columns). Use container queries for anything that is a component and can end up in different places.

What about style queries?

There is also @container style(--variant: dark), which queries the values of CSS custom properties. Support is still uneven, so check caniuse.com before using it in production. Size queries are already safe.

STOS

A blog about front-end, DevOps and tooling

Built on WordPress: custom block theme, Polylang, Yoast SEO. See the WordPress admin in Playground ↗

STOS is a fictional blog — a portfolio concept project. The author and content are samples.