← Lessons

quiz vs the machine

Gold1400

Frontend

CSS Container Queries

Style components by their container size, not the viewport.

5 min read · core · beat Gold to climb

Beyond media queries

Media queries respond to the viewport. But a card might sit in a wide main column on one page and a narrow sidebar on another. The card should adapt to its own space, not the window.

How container queries work

  • Mark an ancestor as a container with container type set to inline size.
  • Inside, write an at container rule that responds to that container width.
  • The component now restyles based on the room it has, anywhere it is placed.

Why it matters

  • Components become truly reusable across layouts.
  • You stop hardcoding breakpoints tied to specific page structures.
  • Container query units like cqw size things relative to the container.

A caveat

A container queries against its nearest ancestor container, so naming containers helps target the right one when they nest.

Key idea

Container queries style a component by its container size, making components adapt to available space rather than the viewport.

Check yourself

Answer to earn rating on the learn ladder.

1. What do container queries respond to?

2. What must you set on the ancestor first?