Skip to content
Velloreth
Web Development 9 min read

CSS Container Queries in Practice

Container queries let components respond to their parent instead of the viewport — setup, size vs inline-size, query units, and migration strategy.

By

Media queries ask one question: how wide is the viewport? That was the right question when the page was the unit of responsiveness. It is the wrong question for a card component that might sit in a wide main column, a narrow sidebar, or a three-up grid on the same page.

Container queries answer the question the component actually has: how much space do I have right now? The same component can stack when it is squeezed into a sidebar and lay out horizontally in the main column, with one stylesheet and no page-level breakpoints.

Support is no longer the concern. Size queries run in every current browser — Chrome and Edge 106+, Safari 16+, Firefox 110+ — with global usage above 95% at time of writing. The interesting part now is using them well.

The problem, concretely

Consider a post card:

<div class="layout">
  <aside class="sidebar">
    <article class="card">...</article>
  </aside>
  <main class="content">
    <article class="card">...</article>
  </main>
</div>

With media queries, both cards get the same layout, because they share a viewport. Writing .sidebar .card overrides is the usual workaround — and it scales badly, because every component now needs a bespoke rule for every context it might appear in.

Container queries move the condition inside the component. One rule set, driven by available width.

Setup in two lines

A container is an element that opts in to being measured:

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

And the shorthand for both at once:

.card-list {
  container: cards / inline-size;
}

Then query it from inside:

@container cards (width > 40rem) {
  .card {
    display: grid;
    grid-template-columns: 12rem 1fr;
  }
}

That is the entire mechanism. The element declaring container-type becomes the query container; its descendants measure themselves against it.

Two rules of resolution matter:

  • An unnamed query (@container (width > 40rem)) uses the nearest ancestor container.
  • A named query uses the nearest ancestor with that name. If no container with that name exists, the block does not apply — there is no fallback to an unnamed container.

Name your containers when a component has more than one candidate ancestor. The default resolution rule is a common source of “why is this query firing” confusion in nested layouts.

size versus inline-size

This is the one decision with real consequences:

ValueQueriesContainment appliedUse it for
inline-sizeWidth onlyStyle + inline-sizeAlmost everything: cards, widgets, columns
sizeWidth and heightStyle + size + layoutViewport-like boxes: maps, chat panes, galleries
normalNo size queriesNoneStyle queries and name-only queries

With inline-size, the element’s height still comes from its content — exactly what you want for a card whose text length varies.

With size, the element gets full size containment: it can no longer be sized by its children. If your container’s height depends on its content, it collapses, and everything inside it collapses with it. That is not a bug; it is what containment means. Only choose size when the container’s box is determined by something other than its contents — a fixed-height panel, a background layer, a map.

The newer values (scroll-state, anchored) exist for scroll-state and anchor-based queries. They solve specific problems; inline-size remains the everyday choice.

Container query units

Inside a container, you also get length units relative to it:

UnitMeaning
cqw1% of the container’s width
cqh1% of the container’s height
cqi1% of the container’s inline size
cqb1% of the container’s block size
cqmin / cqmaxThe smaller / larger of cqi and cqb

cqi is the one you will use constantly. It makes type and spacing fluid within the component, independent of the viewport:

.card-title {
  font-size: max(1.25rem, 1rem + 1.2cqi);
}

.card {
  padding: clamp(1rem, 3cqi, 2rem);
}

The max() here matters: without it, the heading gets unreadably small at the narrow end of its range.

If no query container exists, these units fall back to the corresponding small viewport units for that axis — so a stray cqi in a global stylesheet degrades to viewport-relative behavior instead of breaking.

A component done properly

The full pattern, card and all:

<article class="card">
  <img class="card__media" src="cover.jpg" alt="" />
  <div class="card__body">
    <h3 class="card__title">Post title</h3>
    <p class="card__text">Summary text…</p>
    <a class="card__link" href="/post">Read more</a>
  </div>
</article>
.card {
  container-type: inline-size;
  container-name: card;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  padding: clamp(1rem, 4cqi, 1.5rem);
  border: 1px solid var(--border);
  border-radius: 0.5rem;
}

.card__title {
  font-size: max(1.125rem, 1rem + 1cqi);
  line-height: 1.25;
}

/* wide enough for a horizontal layout */
@container card (width > 28rem) {
  .card {
    flex-direction: row;
    align-items: start;
  }

  .card__media {
    width: 12rem;
    flex-shrink: 0;
  }
}

/* genuinely roomy: two-column body */
@container card (width > 44rem) {
  .card__media {
    width: 18rem;
  }

  .card__body {
    display: grid;
    grid-template-columns: 1fr auto;
    align-items: baseline;
  }
}

Notice what is absent: no knowledge of the page, no breakpoints, no @media. Drop this card into a 200px sidebar or a 1000px hero and it does the right thing by itself.

A detail worth stating explicitly — write the mobile-first condition inside out: base styles for the narrow case, @container blocks for wider cases. The mental model is identical to media queries, just scoped.

Containers inside grid and flex layouts

The combination that makes container queries click for most people: a responsive grid whose children change their internal layout based on the space they were allotted.

.dashboard {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
  gap: 1rem;
}

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

.panel-header {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

@container panel (width > 22rem) {
  .panel-header {
    flex-direction: row;
    justify-content: space-between;
    align-items: baseline;
  }
}

Each panel’s container measures its own grid area — the space the grid gave it, not the viewport. Two panels on a wide screen both expand; when the grid wraps them into narrow columns, each one collapses independently. With media queries you would have needed a breakpoint per column count and would still be guessing which panel is where.

This is also where minmax() and auto-fit earn their keep: the grid decides how many panels fit, and each panel decides what to do with the width it gets. The two mechanisms never need to know about each other.

Flex children work the same way: the container measures the flex item’s laid-out size, so a sidebar widget can restyle itself when the sidebar is narrowed by the page shell, with no rule ever mentioning the shell.

Where media queries still belong

Container queries are not a replacement for @media. The division of labor:

Media queries, when the answer depends on the viewport:

@media (max-width: 48rem) {
  .site-nav { display: none; }
  .site-nav[data-open] { display: block; }
}

@media print {
  .sidebar, .nav { display: none; }
}

@media (prefers-reduced-motion: reduce) {
  * { animation-duration: 0.01ms !important; }
}

Page structure, navigation, print, motion preferences, orientation — none of these should respond to a container.

Container queries, when the answer depends on available space:

  • Cards, list items, tiles
  • Sidebar widgets and dashboard panels
  • Grid children that should change their internal layout at different spans
  • Anything designed to be dropped into an unknown context

If you are writing a selector that reaches outside the component to find its context (.sidebar .widget, .main .widget), that is the smell container queries remove.

Migration strategy

You do not rewrite a codebase’s breakpoints in an afternoon. A sane order:

  1. Audit for context-specific overrides. Grep your stylesheet for rules that combine a layout ancestor with a component class — those are the candidates.
  2. Start with new components. Every new card or widget gets container-type: inline-size from day one. This costs nothing and stops the debt growing.
  3. Migrate the shared components. A card used in three contexts moves as one unit: delete the context overrides, add the container, write one set of @container blocks.
  4. Leave page-level breakpoints alone. The @media rules governing your shell — header, nav, grid columns per viewport — are fine.
  5. Check Tailwind before writing any of it by hand. Tailwind v4 ships container queries natively: mark the parent @container, then write child styles with container variants.
<div class="@container">
  <div class="flex flex-col @md:flex-row @md:items-start">
    …
  </div>
</div>

Named containers work too (@container/main with @md/main:flex), which matters when nested containers could resolve ambiguously.

Pitfalls worth knowing

Containment changes layout, not just matching. container-type is not a passive marker. inline-size applies inline-size containment (the container ignores its children’s inline sizing contributions); size applies full size containment. If an element suddenly sizes differently after you add container-type, this is why — usually you wanted inline-size on a wrapper, not on the element whose height you care about.

Nested containers resolve to the nearest one. In a card inside a grid inside a page shell, an unnamed query from inside the card matches the card’s own container first. That is almost always what you want — and confusing the first time it does not match what you expected. Use container-name and named queries the moment ambiguity appears.

Query units resolve to the nearest container too. 1cqi inside a deeply nested element refers to the innermost container, not the outermost. For page-wide fluid type, keep using viewport units; for component-local fluid type, cqi is correct.

Ordering still applies. Container queries do not raise specificity. Two matching @container blocks resolve by source order like any other rules, so keep them adjacent to the base styles they extend.

Don’t container-query the container itself. A container cannot query itself for size changes — the query applies to descendants. Put the query on children.

Containers are not a performance tool. Containment gives the browser layout information, and in complex trees that can help, but nobody should add container-type expecting a measurable speedup. The reason to use it is correctness of layout, not throughput.

Style queries, briefly

Alongside size queries, the spec allows querying computed styles:

@container style(--theme: dark) {
  .card { border-color: #333; }
}

Comparison of custom properties is the useful subset, and support is newer and less uniform than size queries. The pragmatic take: reach for size queries daily, and treat style queries as worth testing before you depend on them — component variants are usually better expressed with a class.

The habit worth forming

The shift is small and compounding. Next time you reach for @media while styling a component, ask whether the condition is really about the screen or about the space in front of the component. If it is the space, add container-type: inline-size to the wrapper and write the query inside the component.

The page-level breakpoints you already have stay exactly where they are. What changes is that components stop knowing anything about the page — which is the whole point of putting them in components.

Frequently asked questions

Do container queries replace media queries?
No. Container queries replace media queries for component layout decisions — anything that should depend on available space rather than screen size. Page structure, navigation behavior, print styles, and reduced-motion preferences still belong to media queries.
What is the difference between container-type: size and inline-size?
inline-size queries the width only and lets the element still size itself from its content's height. size queries both axes but applies full size containment, which means the element no longer grows to fit its children — heights can collapse if children depend on intrinsic sizing.
What happens if no container exists for a query?
The query does not match and its styles are not applied — except container query length units like cqi, which fall back to the corresponding small viewport unit. That makes units safe to use anywhere, and size queries worth wrapping carefully.
Does Tailwind support container queries?
Yes. Tailwind v4 includes it natively: mark the parent with the @container class, then use container variants like @md:flex for child styles. Named containers work as @container/main with @md/main:flex.