SkillByAIOpen interactive version →

Lesson 12 / 26

Container queries

Style components by their container width instead of the viewport, so one card or widget adapts in any layout.

Container queries vs media queries

Media queries tie layouts to viewport size. Container queries tie layouts to component container size. This makes components more reusable: the same card component adapts differently in a sidebar vs full width.

Using container queries

First, define a container. Then use @container to style children based on that container's width.

.sidebar {
  container-type: inline-size;
}

@container (min-width: 400px) {
  .card {
    display: grid;
    grid-template-columns: 1fr 2fr;
  }
}

@container (max-width: 399px) {
  .card {
    display: block;
  }
}

Quick check

Quick check: What's the advantage of container queries over media queries?

  • They're faster
  • They work on all browsers
  • Components adapt to their container, not viewport
  • They remove the need for CSS
Answer

Components adapt to their container, not viewport — Container queries make reusable components that adapt anywhere.