CSS Container Queries: Responsive Components, Not Just Pages

A card in a sidebar should look different from the same card in a full-width row โ even on the same viewport. That's the problem container queries solve, and they're now supported in every major browser.
Step 1: declare a container
.card-wrap {
container-type: inline-size;
container-name: card;
}Step 2: query it
.card { display: block; }
@container card (min-width: 400px) {
.card { display: grid; grid-template-columns: 120px 1fr; gap: 1rem; }
}Container queries vs media queries
- Media query โ based on viewport
- Container query โ based on a parent element's size
- Use container queries for reusable components that live in multiple layouts
Container query units
cqw, cqh, cqi, cqb let you size things relative to the container itself โ perfect for fluid typography inside a card.
.card h2 { font-size: clamp(1rem, 5cqi, 1.75rem); }Common gotchas
- A container queries its size โ you can't size the container based on its children inside the same query
- container-type: inline-size only watches width; use 'size' for height too
- Don't over-name containers โ naming is optional
Frequently asked questions
Are container queries supported everywhere?
Yes โ all major evergreen browsers (Chrome, Edge, Firefox, Safari) support them. Old IE is the only thing that doesn't, and that's been gone for years.
Should I replace all media queries?
No. Use media queries for page-level layout and container queries for component-level layout.
External references
Enjoyed this article?
Share it with a fellow developer or explore more tutorials in our blog.
More articles