Container queries let an element respond to the size of its own parent container, instead of the size of the entire browser viewport. This solves a problem media queries never could: a reusable component — a card, a widget, a sidebar module — often needs to look different depending on how much space it's actually been given, which has nothing to do with how wide the overall page is.
A card placed in a wide main content area and the exact same card placed in a narrow sidebar need different internal layouts, even though the browser viewport is identical in both cases. That's precisely what container queries are for.
Setting Up a Container
To query a container's size, you first have to opt an element in as a "containment context" using container-type, then write an @container rule that targets elements inside it.
<div class="card-wrapper">
<div class="card">
<img src="photo.jpg" alt="Product" />
<div class="card-body">
<h3>Product Name</h3>
<p>A short description goes here.</p>
</div>
</div>
</div>
.card-wrapper {
container-type: inline-size;
container-name: card-container;
}
.card {
display: flex;
flex-direction: column;
}
/* When the WRAPPER is at least 400px wide, lay the card out horizontally */
@container card-container (min-width: 400px) {
.card {
flex-direction: row;
}
.card img {
width: 40%;
}
}
When .card-wrapper is narrow — say, inside a sidebar — the card stacks its image above its text in a column. The moment that same card is placed somewhere with at least 400px of width to work with — the main content area, for example — it automatically switches to a horizontal layout with the image on the side. The exact same HTML and CSS produce two different layouts purely based on available space, with no JavaScript and no viewport-based media query involved.
Container Queries vs Media Queries
The distinction is simple once it clicks: a media query asks "how wide is the browser window?" A container query asks "how wide is this specific element's parent container?" Media queries are still the right tool for page-level structural changes (see grid template areas for a page-layout example) — container queries are for components that need to be genuinely reusable across different contexts within that same page.
container-type Values
inline-size (used above) only tracks the container's width, which covers the vast majority of real use cases and has the best browser support. size tracks both width and height but requires the container to have an explicit size, since it can't query a dimension it doesn't already know. For most component-level responsive design, inline-size is the one you'll reach for.
