For years, we've used media queries to make responsive designs. But media queries respond to the viewport size, not the container size. This creates problems when components are reused in different layouts.
The Problem
Imagine a card component used in both a sidebar (narrow) and a main content area (wide). With media queries, you can't style it differently based on where it lives — only based on the screen size.
Enter Container Queries
.card-container {
container-type: inline-size;
container-name: card;
}
@container card (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 200px 1fr;
gap: 1rem;
}
}
@container card (max-width: 399px) {
.card {
display: flex;
flex-direction: column;
}
}
Container Query Units
CSS also introduced container query length units:
| Unit | Relative To |
|---|---|
cqw | 1% of container width |
cqh | 1% of container height |
cqi | 1% of container inline size |
cqb | 1% of container block size |
Real-World Use Cases
- Responsive cards — stack vertically in narrow containers, horizontally in wide ones
- Navigation — hamburger menu in sidebar, full nav in header
- Data tables — hide columns when container is too narrow
- Typography — adjust font sizes based on available space
Browser Support
Container queries are now supported in all modern browsers. It's safe to use them in production today with a simple fallback for older browsers.
Container queries are the component-driven approach to responsive design. They let you build truly portable, self-adapting components.