4.1 · Responsive components

Components that fit their box: container queries

Components adapt to the space they get, not to the viewport.

Media queries ask how wide the viewport is. Container queries ask how wide the parent is. A card can then lay itself out for the space it actually gets, whether that’s a sidebar, a grid cell or the full page.

Mark an element as a container with container: card / inline-size, then write @container card (width >= 28rem). Units like cqi (1% of the container’s inline size) scale type and spacing with the container.

Before
/* Depends on the page, not the card */
@media (min-width: 900px) {
  .sidebar .card { … }
  .main .card { … }
}
Now
.wrapper {
  container: card / inline-size;
}

@container card (width >= 28rem) {
  .card { grid-template-columns: 40% 1fr; }
}