Container Queries

Media queries respond to the size of the whole window. Container queries respond to the size of the element a component is placed in. That lets a component — a card, a widget, a form — adapt itself correctly wherever it's used: a narrow sidebar, a wide main column, or a grid cell.

The problem with media queries for components

Imagine a product card that should show its image beside the text when it has room. A media query only knows the window is wide — not whether the card is in a 250px sidebar or an 800px content area. Container queries ask the right question: "how much room does this card have?"

Defining a container and querying it

Try it yourself
Result
  1. Mark the parent as a container with container-type: inline-size (it tracks the container's width).
  2. Write @container (condition) rules for the children.

The same card CSS produces two different layouts, purely based on where it sits.

Named containers

CSS named.css
.sidebar {
  container: sidebar / inline-size;
}

.main {
  container: main / inline-size;
}

@container sidebar (width < 250px) {
  .widget-title { font-size: 1rem; }
}

The container shorthand sets a name and a type. Naming a container lets a query target a specific ancestor rather than the nearest one.

Container query units

Try it yourself
Result

cqi is 1% of the container's inline size (its width in horizontal writing). Like vw for the viewport, but relative to the component's container — so headings and spacing scale with the component.

UnitRelative to
cqi / cqbContainer's inline / block size
cqw / cqhContainer's width / height
cqmin / cqmaxSmaller / larger of the two

Things to know

  • A container can't query itself — only its descendants respond to its size. Wrap a component in a container element if needed.
  • inline-size containment means the container's width can't depend on its children. Containers usually take their width from the layout (they're blocks, grid cells or flex items), which is exactly what you want.
  • Avoid container-type: size unless the container has an explicit height — otherwise it may collapse to zero height.

Style queries

Container queries can also check the value of a custom property on the container — useful for theming variants:

CSS style-query.css
.card-wrapper {
  --theme: dark;
}

@container style(--theme: dark) {
  .card {
    background: #10131c;
    color: white;
  }
}

Media queries vs container queries

Use media queries for…Use container queries for…
Overall page layout (columns, navigation style)Reusable components
User preferences (dark mode, reduced motion)Widgets placed in different-sized slots
Print stylesDesign-system components used across many pages

Try it yourself

Try it yourself
Result