How can I make a layout respond to its container instead of the viewport?
Quick answer
Use a CSS size container and an @container rule when a component should respond to the width available from its parent, rather than the browser window. Set container-type: inline-size on a wrapper, then write a query that styles the wrapper’s descendants at an appropriate width. Unlike a viewport media query, this lets the same component adapt differently in a narrow panel and a wide page.
The question, the details, the next step.
A practical checklist
Identify the parent area whose available width should control the component.
Place a wrapper at that boundary and set
container-type: inline-sizeon it.Write the
@containerrule to style descendants, not the container itself.Choose a threshold based on the component’s content and layout change.
Test the component at different parent widths and verify the wrapper has a usable size.
A few more useful answers
Can a container query replace every media query?
No. Use a container query for a component’s containing size and a media query for viewport or device conditions. They address different kinds of context. [S1]
Should I use `container-type: size` instead?
For queries based on inline size, container-type: inline-size is the relevant setup. size enables broader size queries, with additional size-containment considerations. [S2]
Why does my query not affect the element I put `container-type` on?
Size container queries apply to descendants of the container. Put a wrapper around the element you want the query to style, or target suitable descendants instead. [S2]
Sources
References used for this guide.
- [S1] Using container size and style queries — CSS | MDN developer.mozilla.org · Checked
- [S2] container-type CSS property — CSS | MDN developer.mozilla.org · Checked
