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.

Component Patterns

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

  1. container-type: inline-size establishes width-based containment on the wrapper.
  2. container-name: card lets you target this specific container in nested layouts.
  3. The min-width: 400px condition fires when the wrapper itself is at least 400px wide.
  4. 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.

Try It — CSS Container Query Builder

Open full tool