CSS Container Queries: A Complete Guide for Modern Layouts

DataFmt Team
#css #web-design #responsive #frontend
5 min read

CSS Container Queries: A Complete Guide for Modern Layouts

Container queries shipped in all major browsers in 2023 and are now safe to use everywhere. They are the single biggest CSS improvement of the decade.

The problem they solve

Media queries respond to the viewport. Components, however, often live in different containers (sidebar, main, modal). A card should know how wide its container is — not the screen.

The minimum example

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

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

The .card adapts whenever its parent crosses 400 px wide, regardless of the viewport.

Container query units

UnitMeaning
cqw1% of container width
cqh1% of container height
cqi1% of inline size
cqb1% of block size
cqmin / cqmaxsmaller / larger of cqi & cqb
.title { font-size: clamp(1rem, 4cqi, 2rem); }

Style queries (newer)

You can also query custom properties:

@container style(--theme: dark) {
  .card { background: #111; color: #eee; }
}

When not to use them

  • Top-level page layout — a media query is still simpler.
  • When you only have one breakpoint per component — a flex-wrap may suffice.

Migration tip

Wrap each reusable component in a container-type: inline-size element and progressively replace media queries. Your design system gets dramatically more reusable.

Found this helpful? Try our free tools!

Explore Our Tools →