Container Queries
Style a component by the size of its container, not the viewport β the biggest layout leap since Grid.
Media queries ask “how big is the window?” But a card doesn't care about the window — it cares how much room it was given. The same card might sit in a narrow sidebar on one page and a wide main column on another. Container queries let that card style itself based on its own available width. This is the answer to truly reusable components.
Two steps
First, declare an element a query container. Then query it:
.card-wrapper {
container-type: inline-size;
container-name: card;
}
@container card (min-width: 400px) {
.card { display: grid; grid-template-columns: 120px 1fr; }
}container-type: inline-size means “track my width”. The @container rule then applies when that container crosses the threshold — regardless of viewport size.
Container query units
You also get units relative to the container: cqw, cqh, cqi (inline), cqb (block). font-size: 5cqi scales type to the container's inline size, not the screen.
Example
When to use it
- A developer uses @container to style a sidebar card differently when the sidebar is narrow versus when it is displayed in the main content area.
- A designer builds a reusable product card component that switches from a vertical to horizontal layout based on its own container width.
- A developer moves breakpoints from viewport-based media queries to container queries so components are truly portable between page layouts.
More examples
Basic container query
Registers the wrapper as a named container and switches the card to a horizontal flex layout when the container reaches 400px.
.card-wrapper {
container-type: inline-size;
container-name: card;
}
.card { display: block; }
@container card (min-width: 400px) {
.card {
display: flex;
gap: 16px;
align-items: center;
}
}Component adapts in narrow sidebar
Hides the image and reduces price text when the product card's container is narrower than 280px, ideal in a tight sidebar.
.sidebar { container-type: inline-size; }
.main { container-type: inline-size; }
@container (max-width: 280px) {
.product-card .price { font-size: 0.85rem; }
.product-card img { display: none; }
}Container query units (cqi)
Uses the cqi unit (1% of the container's inline size) with clamp() to fluid-size a title relative to its own container.
.media-card {
container-type: inline-size;
}
.media-card .title {
/* Font scales with the container's inline size */
font-size: clamp(1rem, 5cqi, 1.75rem);
}
Discussion