CSS Container Queries: The Layout Revolution You Should Know
Media queries respond to the viewport. Container queries respond to the element's own size. This changes how we build responsive components. Here's a practical guide to using them today.
# CSS Container Queries: The Layout Revolution You Should Know For years we used media queries tied to the viewport to build responsive layouts. The problem? A card component doesn't know where it'll live—sidebar, main content, full-width hero. Container queries fix this. ## The Problem with Media Queries ```css /* This card responds to the *viewport*, not its container */ @media (min-width: 768px) { .card { flex-direction: row; } } ``` If you put this card in a narrow sidebar on a wide screen, the layout breaks. ## Container Queries to the Rescue ```css /* 1. Declare a containment context */ .card-wrapper { container-type: inline-size; container-name: card; } /* 2. Style based on the container's width */ @container card (min-width: 400px) { .card { display: flex; flex-direction: row; } } ``` Now the card responds to its own container, not the viewport. ## Container Units Container queries also introduce new units: | Unit | Meaning | |---|---| | `cqi` | 1% of container inline size | | `cqb` | 1% of container block size | | `cqw` | 1% of container width | | `cqh` | 1% of container height | ```css .card-title { font-size: clamp(1rem, 4cqi, 1.5rem); } ``` ## Browser Support Container queries have full support in all modern browsers since late 2023. You can use them today without a polyfill. ## When to Use Them - Reusable UI components (cards, sidebars, widgets) - Design systems where components live in unknown contexts - Anywhere you've reached for JavaScript to measure element width Container queries are one of the most impactful CSS features in a decade. Start migrating your component library today.
