Querying the container not the viewport
Media queries respond to the viewport, but a component does not know how wide its slot is. Container queries let an element react to the size of an ancestor container, so the same card looks right in a sidebar or a full width region.
- Declare an ancestor as a container with container type.
- Use the container at rule to apply styles by its size.
- The component adapts wherever it is placed.
Setting up a container
You opt an element into being a query container and choose what it tracks. The most common choice tracks inline size, which is the width in horizontal writing modes.
- container type inline size watches the width.
- A container name lets queries target a specific ancestor.
- Container query length units measure relative to the container.
This decouples a component from the page layout, which is the key to component driven design where pieces move between contexts.
Key idea
Container queries style an element by the measured size of its containing ancestor rather than the viewport, making components adapt correctly anywhere they are placed.