The Limitation of Media Queries
For over a decade, responsive web design relied entirely on Media Queries. Media queries check the size of the browser window (viewport). While useful, this poses problems for component-driven design. A sidebar card needs to look different than a main-content card, even if the viewport size is identical.
Container Queries allow elements to style themselves based on the width of their parent container rather than the viewport.
Implementing Container Queries
First, define the parent container that should be tracked:
.card-parent {
container-type: inline-size;
container-name: card-container;
}
Next, write styles that target the child element when the parent container meets specific sizes:
@container card-container (min-width: 400px) {
.card-layout {
display: flex;
flex-direction: row;
gap: 1.5rem;
}
}