@container
Container queries
A media query asks how wide the screen is. A component rarely cares: the same card is narrow in a sidebar and wide in the main column on the same screen. A container query asks how wide the component’s own container is. Declare an ancestor as a container with container-type, then write @container rules for the things inside it.
Quarterly report
Stacked below 18rem of container, side by side above it.
The window has not changed size, so no media query could do this. The card is asking about the dashed box.
Use it for
- Cards, media objects, and form rows reused across columns of different widths.
- Dashboard widgets that the user can resize or rearrange.
- Design-system components, which cannot know what layout they will be dropped into.
- Anything inside a resizable panel, where the viewport never changes but the space does.
Watch for
- An element cannot query itself. The container is an ancestor, and the rules apply to its descendants — so a component usually needs a wrapper to be the container.
- container-type: inline-size applies size containment on the inline axis: the container’s width can no longer depend on its content. On a shrink-to-fit element — a float, an inline-block, an auto-sized flex item — it collapses to zero.
- Do not make every element a container “just in case”. Containment has a cost, and unnamed queries then match whichever wrapper happens to be nearest.
- Prefer inline-size over size. size also contains the height, so the container needs an explicit one or collapses.
.card-slot { container-type: inline-size; }
.card { display: grid; gap: 0.75rem; }
@container (min-width: 22rem) {
.card { grid-template-columns: 5rem minmax(0, 1fr); align-items: center; }
}