The CSS @container at-rule
The CSS @container at-rule styles an element based on the size of its container, not the whole viewport — e.g. @container (min-width: 400px) { … }. This makes components truly reusable: a card adapts to the space it sits in, whether that is a wide main column or a narrow sidebar. Mark the container with container-type first.
Overview
@container brings responsiveness down to the component level. Where @media asks about the whole viewport, a container query asks about the size of a specific ancestor — so the same card can lay out one way in a roomy main column and another in a cramped sidebar, with no knowledge of the page around it.
It takes two steps. First, mark the element that acts as the container by giving it a container-type — usually inline-size, which means "let me query its width." Then write @container (min-width: 400px) { … }, and those styles apply whenever that container is at least 400px wide.
This is a genuine shift in how reusable components are built. A component styled with container queries is self-contained: drop it anywhere and it adapts to its surroundings automatically. You can name containers (container-name) to query a specific ancestor, and you will often pair container queries for the components with @media for the overall page.
Syntax
/* mark the container */
.card-wrap {
container-type: inline-size;
}
/* style the child by the container's width */
@container (min-width: 400px) {
.card { display: flex; gap: 1rem; }
}
Example
<style>
.wrap { container-type: inline-size; }
.card { background: #94a3b8; color: #fff; padding: 18px; border-radius: 10px; font: 600 14px system-ui, sans-serif; }
@container (min-width: 300px) {
.card { background: #1c7ce9; }
}
</style>
<div class="wrap"><div class="card">My container is at least 300px wide, so I am blue.</div></div>
Best practices
- Set
container-type: inline-sizeon the parent before writing container queries against it. - Name containers with
container-name(or thecontainershorthand) when you need to target a specific ancestor. - Use container queries for reusable components and @media for page-level layout — they complement each other.
- They are ideal for design systems, where a component must work in many different-sized slots.
Frequently asked questions
What is a CSS container query?
@container. It makes components adapt to wherever they are placed.What is the difference between @container and @media?
@container responds to a specific ancestor element's size — better for reusable components.How do I set up a container query?
container-type: inline-size, then write @container (min-width: 400px) { … } for the children.What does container-type do?
inline-size lets you query its width; size queries both dimensions.