Media queries ask how big the screen is. Container queries ask how much room this component actually has, which is the question we were trying to answer all along.
The setup
Declare a containment context on the parent, then query it from the child. The parent opts in with container-type, and the child responds with @container. Two properties, and a card can finally lay itself out based on its own space instead of the viewport.
Where it pays off immediately
- Cards that appear in both a wide grid and a narrow sidebar.
- Design system components shipped without knowing their context.
- Dashboard widgets users can resize.
Things to watch
An inline-size container cannot be sized by its own children in that axis, which surprises people the first time a layout collapses. Name your containers when nesting, or a query will match the wrong ancestor.
Browser support is broad now, so the remaining question is whether your component library is structured to take advantage of it. Most are not, and that refactor is the real cost.
Leave a Comment