Chapter 24 of 33

Container Queries

In Responsive Design & Media Queries we changed layouts based on the width of the viewport. That works well for page-level structure. But modern websites are built from reusable components: a course card, a product tile, a profile box. The same card might appear in a wide main column, in a narrow sidebar, and in a three-column grid, all on the same page and at the same viewport width.

A media query can't help here, because the viewport width is the same for all three cards. What we really want to ask is: "how much space does this component have?" That is exactly what container queries do. In this chapter we learn how to declare containers, write @container rules, use container query units like cqi, and use the newer style queries, along with the traps that catch almost everyone the first time.


The Problem with Media Queries for Components

Viewport = 1200px (same for everything below)

┌────────────┬─────────────────────────────────────────┐
│ Sidebar    │ Main column                             │
│ 260px      │ 900px                                   │
│ ┌────────┐ │ ┌──────────┬──────────────────────────┐ │
│ │ image  │ │ │  image   │ Title                    │ │
│ │ Title  │ │ │          │ Description … Price      │ │
│ │ Price  │ │ └──────────┴──────────────────────────┘ │
│ └────────┘ │                                         │
└────────────┴─────────────────────────────────────────┘
  narrow card should stack     wide card should go horizontal

With media queries you would need special classes like .card--in-sidebar and .card--in-main, and you'd have to update them every time the page layout changes. The card is not truly reusable: it depends on knowing where it is placed.

A container query applies styles to an element based on the size (or style) of one of its ancestor elements, called the query container, instead of the size of the viewport.

With container queries the card says: "if my container is at least 400px wide, go horizontal". Put it anywhere and it adapts correctly.


Step 1: Declare a Container

Elements are not size containers by default. You opt in with container-type on the parent (or any ancestor) of the component:

.card-slot {
  container-type: inline-size;
}
container-typeYou can querySide effect
normal (default)No size queries (style queries only, see later)None
inline-sizeWidth (the inline dimension)The element's width no longer depends on its content
sizeWidth and heightNeither width nor height depends on its content

You will use inline-size almost all the time. Why the side effect? To avoid an infinite loop. If a container's width depended on its children, and the children's styles depended on the container's width, a query could change the children, which changes the width, which flips the query back, and so on. So the browser applies size containment: the container's size is calculated as if it had no content, and only then are the children styled.

Naming containers

You can give a container a name with container-name, or use the container shorthand (name / type):

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

/* same thing, shorthand */
.card-slot {
  container: card / inline-size;
}

Names are useful when containers are nested and you want to query a specific one instead of the nearest one.


Step 2: Write @container Rules

The syntax looks just like a media query, with the same range syntax:

@container (width >= 400px) {
  .card {
    grid-template-columns: 180px 1fr;
  }
}

/* query a named container */
@container card (width >= 400px) { … }

/* old min-/max- style also works */
@container (min-width: 400px) { … }

Rules inside @container are applied to elements whose nearest ancestor container (or nearest ancestor with that name) matches the condition. You can combine conditions with and, or and not, and query width, inline-size, height, block-size, aspect-ratio and orientation. Anything that involves the height (height, block-size, aspect-ratio, orientation) needs a container-type: size container.


A Complete Example: One Card, Two Layouts

<div class="layout">
  <aside class="card-slot">
    <article class="card">
      <div class="card__img"></div>
      <div>
        <h3 class="card__title">Python Basics</h3>
        <p class="card__text">Variables to functions, step by step.</p>
        <p class="price">Free</p>
      </div>
    </article>
  </aside>

  <main class="card-slot">
    <!-- exactly the same card markup -->
  </main>
</div>
* { box-sizing: border-box; }

.layout {
  display: grid;
  grid-template-columns: 260px 1fr;
  gap: 24px;
}

/* every slot that can hold a card is a container */
.card-slot {
  container: card / inline-size;
}

/* base: narrow, stacked card */
.card {
  display: grid;
  gap: 12px;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 12px;
}

.card__img {
  aspect-ratio: 16 / 9;
  background: linear-gradient(135deg, #0ea5e9, #6366f1);
  border-radius: 6px;
}

.card__title {
  margin: 0;
  font-size: 1.1rem;
}

/* wide container: image on the left, text on the right */
@container card (width >= 400px) {
  .card {
    grid-template-columns: 180px 1fr;
    align-items: start;
  }
  .card__title {
    font-size: 1.4rem;
  }
}

Rendered in Chrome with a 900px-wide viewport (and the default 8px body margin), the main slot is 900 − 16 − 260 − 24 = 600px wide:

┌──────────────┐  ┌─────────────────────────────────────────────┐
│ ┌──────────┐ │  │ ┌──────────┐  Python Basics (22.4px)        │
│ │  image   │ │  │ │  image   │  Variables to functions, …     │
│ └──────────┘ │  │ └──────────┘  Free                           │
│ Python Basics│  └─────────────────────────────────────────────┘
│ Variables …  │       main slot: 600px wide → query matches
│ Free         │
└──────────────┘
 sidebar slot: 260px → query doesn't match (stacked, title 17.6px)

Same HTML, same CSS, same viewport, two different layouts. Move the card anywhere else and it chooses the right layout on its own.

Notice that the .card-slot elements are the containers and the .card inside is what we style. This is a rule, not a style choice, as we see next.


The Golden Rule: A Container Can't Style Itself

An @container query never applies to the container element itself; it only affects the container's descendants.

.box {
  container-type: inline-size;
  width: 500px;
}

/* ❌ .box is the container being measured, so this never styles .box */
@container (width > 300px) {
  .box { background: red; }
}

We tested this: .box stays unstyled even though it is 500px wide. The query looks for a container among .box's ancestors, and there is none. (Again, this prevents loops: if a container could restyle itself, changing its own width could flip its own query.)

That is why the usual pattern is a wrapper element as the container, and the component inside it:

.card-slot   ← container (measured)
  └─ .card   ← styled by @container rules
       └─ …  ← also styleable

The #1 Trap: Containers That Collapse to Zero

Because of size containment, a container's width must come from outside (from its parent or a fixed width), never from its content. If the element would normally be "as wide as its content", it shrinks to zero:

/* ❌ inline-block is shrink-to-fit: its width comes from its content */
.badge-wrap {
  display: inline-block;
  container-type: inline-size;
}

/* ❌ a flex item with flex: none is sized by its content */
.toolbar > .item {
  flex: none;
  container-type: inline-size;
}

In Chrome, both of these measured 0px wide, with their text spilling out. The same happened with a float, an absolutely positioned element with no width, and a grid item in an auto column (all 0px in our test).

Safe containers are elements whose width is decided by the layout around them:

  • Normal block elements (div, section, main...), which fill their parent's width.

  • Grid items in fr or fixed-size tracks (like the slots in our example).

  • Flex items with a definite size, such as flex: 1 or an explicit width.

And for container-type: size, the height must also be set from outside (a fixed height, or a stretched grid/flex item). Otherwise the container is 0px tall. This is why size is rarely used.


Container Query Units

Viewport units like vw are relative to the viewport. Container query units are the same idea, relative to the nearest size container:

UnitEquals
cqw1% of the container's width
cqh1% of the container's height
cqi1% of the container's inline size (width in horizontal writing)
cqb1% of the container's block size (height in horizontal writing)
cqminThe smaller of cqi and cqb
cqmaxThe larger of cqi and cqb

Worked example: inside a 500px-wide inline-size container, font-size: 5cqi = 5% of 500 = 25px, and width: 50cqw = 250px (both confirmed in Chrome).

The most common use is text that scales with its component, kept within limits by clamp():

.price {
  font-size: clamp(1rem, 6cqi, 2rem);
}
sidebar slot 260px: 6% of 260 = 15.6px → below 16px min  → 16px
main slot    600px: 6% of 600 = 36px    → above 32px max → 32px

Adding this rule to the example, Chrome produced exactly these sizes for the two cards. Prefer cqi over cqw: it follows the writing direction, and most containers are inline-size containers anyway (cqh/cqb need a size container to mean anything).

If there is no suitable container at all, the units fall back to the small viewport units (svw, svh...), so 10cqw with no container behaves like 10svw. Our test with no container gave 10% of the window width.


Nested and Named Containers

An unnamed @container query uses the nearest ancestor size container. A named query skips to the nearest ancestor with that name.

.sidebar {
  container: sidebar / inline-size;
  width: 300px;
}

.widget {
  container-type: inline-size;
  width: 500px;            /* wider than the sidebar, for the demo */
}

/* nearest container = .widget (500px) */
@container (width > 450px) {
  .title { font-size: 30px; }
}

/* skip to the container named sidebar (300px) */
@container sidebar (width < 400px) {
  .title { color: blue; }
}
<div class="sidebar">
  <div class="widget">
    <p class="title">Hello</p>
  </div>
</div>

Result: .title is both 30px (the widget is 500px > 450px) and blue (the sidebar is 300px < 400px). Each query found a different container.

Brand-new in 2026: you can also write a query with only a name and no condition, like @container sidebar { … }, meaning "if I'm inside a container named sidebar". This reached Baseline (newly available) in May 2026, so check your audience's browsers before relying on it.


Style Queries

Size isn't the only thing you can query. Style queries check the value of a custom property on the container:

.panel {
  --theme: dark;
}

@container style(--theme: dark) {
  .panel-content {
    background: black;
    color: white;
  }
}

Things to know:

  • --theme is a custom property (a CSS variable). The next chapter, CSS Variables (Custom Properties), explains them fully; for now, think of it as a named value you set yourself.

  • No container-type is needed: every element is a style container by default (that's what container-type: normal means). An unnamed style query checks the nearest ancestor, i.e. usually the parent.

  • Browsers currently support style queries only for custom properties. A query like style(display: flex) is in the specification but not implemented anywhere yet.

  • Support: Chrome/Edge 111, Safari 18 and Firefox 151. Style queries became Baseline newly available in May 2026, so older browsers (still in use) ignore them. Treat them as an enhancement.

There are also scroll-state queries (container-type: scroll-state), which style descendants when a container is stuck (position: sticky), snapped or scrollable. As of late 2026 they work only in Chromium browsers (Chrome, Edge), so they are not Baseline yet.


Browser Support

FeatureChrome / EdgeFirefoxSafariBaseline status (Nov 2026)
Size queries + cq* units10511016Widely available (since Aug 2025)
Style queries (custom properties)11115118Newly available (May 2026)
Name-only queries14814926.4Newly available (May 2026)
Scroll-state queriesYesNoNoNot Baseline

Size container queries are safe for production. If you must support very old browsers, write a sensible base layout (the stacked card) first; browsers that don't understand @container simply ignore the block and keep the base.


Container Queries vs Media Queries

Media queriesContainer queries
MeasuresThe viewport / deviceAn ancestor element (the container)
Setup neededNonecontainer-type on an ancestor
Can check user preferences, print, hover, pointerYesNo
Best forPage layout, global settingsReusable components
Unitsvw, vh, dvh …cqi, cqb, cqw …
Can style the measured element itselfYes (the viewport isn't an element)No, only descendants

They work together: use media queries for the page (how many columns, where the sidebar goes, dark mode) and container queries for components (how a card arranges itself in whatever space it gets).


Common Mistakes

  • Forgetting container-type. Without it, @container size queries have nothing to measure and never match.

  • Trying to style the container itself. Queries only affect descendants; add a wrapper.

  • Making a shrink-to-fit element a container. inline-block, floats, flex: none items and auto grid tracks collapse to 0px.

  • Using container-type: size without a height. The container becomes 0px tall.

  • Expecting style queries on normal properties. Only custom properties work today.

  • Replacing every media query. Things like dark mode, print and the overall page grid still belong to media queries.


Interview & Exam Questions

1. What problem do container queries solve that media queries can't?

Media queries respond only to the viewport, so a component can't adapt to the space it actually has. The same component placed in a narrow sidebar and a wide main column sees the same viewport width. Container queries let a component respond to the size of its own container, making it truly reusable.

2. Why does container-type: inline-size make an inline-block element collapse?

It applies inline-size containment: the element's width is computed as if it had no content. An inline-block gets its width from its content (shrink-to-fit), so with no content counted it becomes 0px wide. Containers need their width to come from outside, e.g. a block element filling its parent.

3. Can an element style itself using a container query on its own size? Why?

No. @container rules look for a query container among the element's ancestors, so they only style descendants. Allowing self-styling could create loops, where the style changes the size and the size flips the query again.

4. A container is 640px wide. What is font-size: clamp(14px, 3cqi, 24px)?

3cqi = 3% of 640 = 19.2px, which lies between 14px and 24px, so the font size is 19.2px.

5. What is the difference between container-type: size and inline-size?

inline-size lets you query only the width (inline dimension) and contains only the width; height still comes from the content. size lets you query width and height but contains both, so the element needs an explicitly determined height or it collapses to zero height.

6. What do container style queries check, and what is their support status in 2026?

They check computed values of custom properties on the container, e.g. @container style(--theme: dark). Querying normal properties isn't implemented in any browser yet. With Firefox 151 they became Baseline newly available in May 2026 (Chrome 111+, Safari 18+).


Summary

  • Container queries let components respond to their container's size, not the viewport's.

  • Declare containers with container-type: inline-size (usually) and optionally container-name, or the shorthand container: name / type.

  • Write @container [name] (condition) { … }, using the same range syntax as media queries.

  • Queries style only descendants, never the container itself.

  • Size containment means the container's width must come from outside; shrink-to-fit containers collapse to zero.

  • cqi, cqw, cqb, cqh, cqmin, cqmax are percentages of the container's size.

  • Size queries are widely available; style queries (custom properties only) and name-only queries became Baseline in 2026; scroll-state queries are Chromium-only.

Style queries gave us a first look at custom properties. In the next chapter, CSS Variables (Custom Properties), we learn how to use them properly: defining them, inheritance, fallbacks, theming, and updating them from JavaScript.