Container Queries
Media queries respond to the size of the whole window. Container queries respond to the size of the element a component is placed in. That lets a component — a card, a widget, a form — adapt itself correctly wherever it's used: a narrow sidebar, a wide main column, or a grid cell.
The problem with media queries for components
Imagine a product card that should show its image beside the text when it has room. A media query only knows the window is wide — not whether the card is in a 250px sidebar or an 800px content area. Container queries ask the right question: "how much room does this card have?"
Defining a container and querying it
- Mark the parent as a container with
container-type: inline-size(it tracks the container's width). - Write
@container (condition)rules for the children.
The same card CSS produces two different layouts, purely based on where it sits.
Named containers
.sidebar {
container: sidebar / inline-size;
}
.main {
container: main / inline-size;
}
@container sidebar (width < 250px) {
.widget-title { font-size: 1rem; }
}
The container shorthand sets a name and a type. Naming a container lets a query target a specific ancestor rather than the nearest one.
Container query units
cqi is 1% of the container's inline size (its width in horizontal writing). Like vw for the viewport, but relative to the component's container — so headings and spacing scale with the component.
| Unit | Relative to |
|---|---|
cqi / cqb | Container's inline / block size |
cqw / cqh | Container's width / height |
cqmin / cqmax | Smaller / larger of the two |
Things to know
- A container can't query itself — only its descendants respond to its size. Wrap a component in a container element if needed.
inline-sizecontainment means the container's width can't depend on its children. Containers usually take their width from the layout (they're blocks, grid cells or flex items), which is exactly what you want.- Avoid
container-type: sizeunless the container has an explicit height — otherwise it may collapse to zero height.
Style queries
Container queries can also check the value of a custom property on the container — useful for theming variants:
.card-wrapper {
--theme: dark;
}
@container style(--theme: dark) {
.card {
background: #10131c;
color: white;
}
}
Media queries vs container queries
| Use media queries for… | Use container queries for… |
|---|---|
| Overall page layout (columns, navigation style) | Reusable components |
| User preferences (dark mode, reduced motion) | Widgets placed in different-sized slots |
| Print styles | Design-system components used across many pages |