
Preparing Design Systems for CSS Container Queries
Media queries have powered responsive web design for over a decade. However, media queries only evaluate the global browser viewport. If a responsive card component is placed inside a narrow 300px sidebar, media queries still evaluate the 1440px desktop viewport, rendering wide desktop layouts inside a cramped space.
CSS Container Queries allow elements to respond directly to the dimensions of their parent container rather than the browser window.
Example
<aside class="sidebar">
<div class="card-container">
<article class="post-card">...</article>
</div>
</aside>
Implementation
We declare a containment context using container-type: inline-size, and query that container with @container:
.card-container {
container-type: inline-size;
container-name: card;
}
.post-card {
display: flex;
flex-direction: column;
gap: 12px;
}
/* When the parent container is at least 450px wide */
@container card (min-width: 450px) {
.post-card {
flex-direction: row;
align-items: center;
}
}
Main Point: Container queries decouple component styling from the viewport, making design system components truly modular and self-adapting anywhere on the page.
Credits
Photo by Luca Bravo on Unsplash