Responsive Card Component with Container Query
Build a card component that switches from vertical to horizontal layout based on its container width using CSS container queries with min-width: 400px.
Detailed Explanation
Responsive Card with Container Queries
Container queries are perfect for card components that appear in different layout contexts -- a narrow sidebar, a medium content area, or a wide hero section.
The CSS
.card-wrapper {
container-type: inline-size;
container-name: card;
}
@container card (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 200px 1fr;
gap: 1rem;
}
}
How It Works
By default (in narrow containers), the card stacks its image and text vertically. When the container reaches 400px wide, the card switches to a horizontal grid layout with the image on the left and text on the right.
Why Container Queries Win Here
With media queries, you would need to know exactly which viewport widths correspond to your card being wide enough. If the card moves from a 3-column grid to a 2-column grid, all your breakpoints break. Container queries solve this because the card responds to its own space, not the viewport.
Key Points
container-type: inline-sizeestablishes width-based containment on the wrapper.container-name: cardlets you target this specific container in nested layouts.- The
min-width: 400pxcondition fires when the wrapper itself is at least 400px wide. - You can add more breakpoints (e.g., 600px for an even wider layout) the same way.
Use Case
Use this pattern when building a card component that appears in sidebars, main content areas, and full-width sections. The card adapts its layout to match the available space without any JavaScript or viewport-based media queries.