We've come a long way from the dark ages of floats and clearfixes. CSS Grid and Flexbox changed the game, but Container Queries are the true revolution for modern, component-based design systems.
@container is the new @media
Historically, responsive design meant using @media queries to check the width of the entire browser viewport. But in a component-driven world (like React), a "Card" component might be placed in a narrow sidebar or a wide main content area. Media queries fail here.
Container Queries solve this by allowing elements to respond to the width of their parent container, rather than the viewport.
/* Define the container */
.card-wrapper {
container-type: inline-size;
container-name: card;
}
/* Style the child based on the container's width */
.card {
display: flex;
flex-direction: column; /* Default: Stacked */
}
@container card (min-width: 400px) {
.card {
flex-direction: row; /* Wide enough: Side by side! */
}
}
The Subgrid Magic
Alongside container queries, subgrid has finally achieved cross-browser support. Subgrid allows child elements to align themselves to the tracks of their parent's CSS Grid. This ensures that a row of cards will perfectly align their internal headers and footers, regardless of the text length inside them. CSS has never been more powerful.