Skip to the content

Container Queries

A component should adapt to the width of its slot, not the width of the screen. The same card can sit in a 280px sidebar and a 900px feed. The cq prop answers "how wide is my slot"; the viewport prefixes and viewportMedias answer "how wide is the screen".
Guides

The rule

  • Mark the slot with containment="inline-size", on the immediate wrapper of the adapting component.
  • Declare per-width styles with cq on any descendant, using the same props as the base style.
  • Never put containment on a page shell (GlobalStyle, a layout root, main): the browser would then watch the whole page for layout changes. An automated check forbids it.
  • Reach for cq whenever a component can appear at more than one width on the same screen.

How it works

cq is mobile-first. The base style is the narrow-slot design; wider slots opt in through ascending min-width container queries keyed by theme.containerSizes: xs 240px, sm 360px, md 480px, lg 640px, xl 900px. This scale is separate from the viewport breakpoints.

<Flex containment="inline-size">
  <Card title="Order" cq={{ sm: { p: 'large' } }} />
</Flex>

containment="inline-size" measures width only, the common and cheapest case. "size" measures both axes; a second word names the container ("inline-size card").

Card and UploadCard are containers already, so content inside them can use cq with no wrapper:

Narrow

The meta row stacks below the sm container size.

Meta A

Meta B

Wide

Same markup, laid out horizontally.

Meta A

Meta B

cq is plain CSS: the server emits static rules and the browser resolves them, so it is safe under server rendering. A browser without @container support ignores the rules and renders the base — the mobile design — never a broken state.

To explore a story by slot width, Storybook's resizable slot (Card → ResizableSlot, UploadCard → SlotAdaptive) lets you drag the slot while the viewport stays fixed.

Pitfalls

  • A component querying its own width → an element measures against its nearest ancestor container; put containment one level up.
  • Swapping the DOM tree by width with cq → cq changes presentation only. A different element tree, a portal or a focus trap stays a JavaScript branch with useMediaQuery.
  • Responsive borders through cq → border props are excluded from every responsive channel; use a different variant instead.

See also