Definition
Container queries let styles respond to the size of a named ancestor (the containment context) rather than the viewport. The ancestor is declared with container-type and optionally named with container-name. Children then use @container rules to apply styles when the ancestor meets a condition.
.card-wrapper { container-type: inline-size; container-name: card; }
@container card (min-width: 400px) {
.card { flex-direction: row; }
}container-type values:
inline-size: enables queries on the inline axis (width in horizontal writing modes). Most common.size: enables queries on both axes. Requires the container to have a definite block size.normal: enables style queries only; no size queries.
Style queries (@container style(--variant: compact)) query custom property values, not dimensions. They are useful for theming component variants without adding class permutations.
Container queries landed in all major browsers in 2023. They do not apply to the queried container itself, only to its descendants.
When it applies
Use container queries for components that appear in multiple layout contexts with different widths (a card in a sidebar vs. a full-width feed). Use viewport media queries for page-shell layout decisions. Combining both is correct; they solve different problems.
Example
.sidebar { container-type: inline-size; container-name: sidebar; }
@container sidebar (min-width: 300px) {
.nav-link { display: flex; gap: 8px; }
}
@container sidebar (max-width: 299px) {
.nav-link span { display: none; }
}Related concepts
- grid-template - grid tracks can adapt to container size via
frandminmax(). - viewport - container queries complement viewport media queries, they do not replace them.
- cascade -
@containerrules participate in the cascade like@mediarules. - custom-property - style container queries read custom property values.
- css - the CSS deep-dive.
Citing this term
See Container Query (llmbestpractices.com/glossary/container-query).