Skip to content
GreenSnippets

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
.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

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.