Card that adapts to its container with container queries
Switch a card from stacked to side-by-side based on the space it has, not the viewport.
- CSS
- GreenSnippets
- MIT
.card-wrap {
container-type: inline-size;
container-name: card;
}
.card {
display: grid;
gap: 1rem;
}
@container card (min-width: 32rem) {
.card {
grid-template-columns: 12rem 1fr;
align-items: start;
}
}Example / expected output
/* Narrow container: image above text. 32rem or wider: image beside text. */How it works
Media queries react to the viewport, which is wrong for components used in both a narrow sidebar and a wide main column. Declare a container, then query it. container-type: inline-size lets the browser measure the width without the card's own content affecting the result.
This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.
Related snippets
- CSS
Fluid typography with clamp()
Scale font size smoothly between a minimum and maximum as the viewport grows, with no media queries.
- CSS
CSS-only scroll-snap carousel
A horizontally scrolling gallery that snaps to each card, with no JavaScript.
- CSS
Respect prefers-reduced-motion
Turn off or shorten animations for users who ask their system for less motion.
- CSS
A small modern CSS reset
Sensible defaults for box sizing, media, form fonts and text wrapping in a dozen lines.

