Container Queries
Container queries let you style a component based on the size of its parent container rather than the viewport.
The problem with media queries
css
/* media query - based on viewport */
@media (min-width: 768px) {
.card { display: flex; }
}
/* problem: what if .card is in a narrow sidebar on a wide screen? */Container queries - component-aware
css
/* 1 - define a containment context */
.card-wrapper {
container-type: inline-size;
container-name: card; /* optional */
}
/* 2 - query the container, not the viewport */
@container card (min-width: 400px) {
.card {
display: flex;
flex-direction: row;
}
}
@container card (max-width: 399px) {
.card {
display: block;
}
}Why this matters
text
Sidebar (300px wide) Main content (800px wide)
┌──────────────────┐ ┌─────────────────────────────┐
│ .card - stacked │ │ .card - horizontal layout │
│ (container 300px)│ │ (container 800px) │
└──────────────────┘ └─────────────────────────────┘
/* same component, same CSS - adapts to its context */Container units
css
/* units relative to the container size */
.card h2 { font-size: 5cqi; } /* 5% of container inline size */| Unit | Relative to |
|---|---|
cqw | Container width |
cqh | Container height |
cqi | Container inline size |
cqb | Container block size |
Comparison
| Media Query | Container Query | |
|---|---|---|
| Based on | Viewport | Parent container |
| Component reuse | Hard | Easy |
| Browser support | All | All modern browsers (Baseline since 2023) |
Container queries are the biggest layout improvement in CSS in years. They finally make truly reusable components possible without JavaScript resize observers.
updated
did you know it?