A card can have plenty of room in a page’s main area and little room in its sidebar, even when the viewport is wide. `@container` applies CSS conditions based on a containing ancestor’s dimensions rather than the viewport. Unlike a media query, it lets the same component respond to where it is placed. section 4.1.3
First, mark an ancestor with `container-type: inline-size` for width-based queries, or `container-type: size` for width or height queries. Then put the conditional styles in an `@container` rule. Give the component its ordinary styles outside the rule; use the query for the layout change. Container names can scope a query when several containers might match. section 4.1.3
One card, two placements
A page puts the same `article.card` markup inside `main` and `aside`. Both ancestors have `container-type: inline-size`. At `@container (min-width: 400px)`, the card becomes a two-column grid with its image beside the text. Below that threshold, its base layout remains in effect. The cards can therefore differ on the same viewport. section 4.1.3
Listing 4.3 CSS Container Queries in action
body {
font-family: system-ui, sans-serif;
display: grid;
grid-template-columns: 2fr 1fr;
gap: 2rem;
padding: 1rem;
}
main {
display: grid;
gap: 1rem;
container-type: inline-size; #1
}
aside {
container-type: inline-size; #1
}
article.card { #2
border: 1px solid #ccc; #2
border-radius: 12px; #2
padding: 1rem; #2
background: #fafafa; #2
} #2
@container (min-width: 400px) { #3
article.card { #4
display: grid; #4
grid-template-columns: 120px 1fr; #4
gap: 1rem; #4
} #4
article.card img { #4
width: 100%; #4
border-radius: 8px; #4
} #4
}
The stylesheet identifies the two query containers, defines the card’s base appearance, and confines its two-column layout to the container-width condition. section 4.1.3
For measurements relative to a container, pair queries with units such as `cqw` and `cqh`. Grid can likewise change a gallery’s columns according to its own container width instead of global breakpoints. Keep viewport concerns separate: `dvh` addresses changes in mobile browser UI, not component width. section 4.1.3 section 4.2.2

