Skip to content
css questions

CSS · 10 of 10senior~1 min

What are CSS container queries and how do they differ from media queries?

#layout#responsive#modern

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 */
UnitRelative to
cqwContainer width
cqhContainer height
cqiContainer inline size
cqbContainer block size

Comparison

Media QueryContainer Query
Based onViewportParent container
Component reuseHardEasy
Browser supportAllAll 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?

related questions