Container Query Card Responsive
Make a card component responsive to its container size rather than the viewport using CSS container queries.
Code
.card-container {
container-type: inline-size;
container-name: card;
}
.card {
display: flex;
flex-direction: column;
gap: 1rem;
}
@container card (min-width: 400px) {
.card {
flex-direction: row;
align-items: center;
}
.card-image { flex: 0 0 200px; }
}
@container card (min-width: 600px) {
.card { gap: 2rem; }
.card-title { font-size: 1.5rem; }
}How it works
display: flex distributes the children along one axis, and the alignment properties decide how leftovers are handled.
@container queries size the component against its container instead of the viewport.
gap spaces grid/flex items without margins on the children.
@container queries drive the responsive behavior from the parent element’s size rather than the viewport.
The rules target .card-container, container-type: inline-size; container-name: card; } .card, .card, flex-direction: row; align-items: center; } .card-image, } @container card (min-width: 600px) — each selector names the element it restyles, in source order.
Interactive Tools for This Topic
FAQ
- Which elements does this stylesheet target?
- The rules bind to `.card-container`, `container-type: inline-size; container-name: card; } .card`, `.card`, `flex-direction: row; align-items: center; } .card-image`; when two rules tie in specificity, the one written later in the file wins.
Report a problem with this exampleOpens a pre-filled issue on GitHub.