CSS Container Queries
Container queries let a component respond to the space available around it. Use them to make reusable cards and panels adapt to their own width, wherever they appear.
Container queries and media queries
A media query checks the viewport or user preferences. A size container query checks the dimensions of an ancestor element, so a component can change when its own layout space changes even if the overall window does not.
Establish a query container
Set container-type: inline-size on a wrapper. Its descendants can then query the wrapper's available inline size, which is usually its width in a horizontal writing mode.
.card-list {
container-type: inline-size;
}
The query applies to descendants of the container. The container itself cannot use its own size query to style itself.
Change a card when its container grows
Start with a compact, single-column card. When the surrounding list is wide enough, use @container to place its image and copy side by side.
.card-list {
container-type: inline-size;
}
.profile-card {
display: grid;
gap: 1rem;
}
@container (min-width: 32rem) {
.profile-card {
grid-template-columns: 9rem 1fr;
align-items: center;
}
}
Put .profile-card inside an element with the card-list class. The card switches layout when that ancestor reaches the chosen width, not when the viewport reaches it.
Name containers for clearer rules
When a component has several possible ancestors, give the intended container a name. A named query only matches a suitable ancestor with that name.
.article-layout {
container: article / inline-size;
}
@container article (min-width: 45rem) {
.article-callout {
display: grid;
grid-template-columns: 1fr 2fr;
gap: 1.5rem;
}
}
Choose container or viewport rules
Use a container query when the component should adapt to its parent, such as a card reused in a sidebar and a main column. Use a media query for page-wide layout decisions or conditions such as reduced motion.
container-type. If no matching container exists, the conditional styles do not apply.Practice with a reusable component
Add a container around a card, set container-type: inline-size, and resize the card's parent. Then add a named container and compare its behavior with a viewport media query. For the page-level version, see responsive CSS design; for two-dimensional page layouts, continue to CSS Grid.