CodePark/ questions / Modern CSS
START PRACTICINGPRACTICE
Frontend question · CSS & HTML › Modern CSS

What are container queries and how do they differ from media queries?

.card-wrapper { container-type: inline-size; }

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

Media queries respond to the size of the viewport, the browser window. Container queries respond to the size of an ancestor container. So a component adapts to the space it actually gets. The same card can be stacked in a narrow sidebar and side-by-side in a wide main column, on the same screen.

How to use them:

  • Mark an ancestor with container-type: inline-size (or size).
  • Optionally name it with container-name.
  • Write @container (min-width: 400px) { ... }.

An element can't query its own size, only an ancestor's. That is why a wrapper element is common. Container query units such as cqi size things relative to the container.

All current evergreen browsers support them. Evergreen browsers update themselves automatically, like Chrome, Firefox, Safari and Edge. Media queries are still right for page-level layout and for user preferences like prefers-color-scheme.

  • Container queries check the container's size, not the viewport.
  • Set container-type on an ancestor, then write @container rules.
  • An element can't query its own size.
  • They make components reusable. Media queries are still for page layout and user preferences.