Sub topic 1
Why Components Should Respond to Their Container
Most responsive CSS answers one question: how wide is the browser window? A component such as a card, a comment, or a product tile usually cares about a different question: how much room do I have here? This chapter explains why those two questions diverge, what goes wrong when you answer the wrong one, and how container queries change the model. The rest of the tutorial builds on that change.
Prerequisites
This chapter assumes you are comfortable with the following:
- CSS selectors and the cascade, including how specificity decides between competing rules.
- Media queries and viewport units such as
vwandvh. - CSS custom properties: declaring
--namevalues and reading them withvar(). - Basic flexbox or grid layout.
- The
clamp()function, which later chapters use for fluid sizing.
No container query syntax is assumed. You will see a short preview of it here, and later chapters cover each part in detail.
The problem: one component, many places
Consider a card with an image on the left and text on the right when there is space, and a stacked layout when there is not. You build it once and reuse it in three places:
- The main content column of an article page, about 45rem wide.
- A sidebar, about 18rem wide.
- A three-column grid on a landing page, where each cell is about 22rem wide.
The card's own design is the same everywhere. What differs is the space it is given. A component library author writing the card does not know which of these slots a team will put it in, and often does not know the page layout at all.
The markup for the card is simple:
<div class="card-wrapper">
<article class="card">
<h2>Title</h2>
<p>Body text that reflows with the wrapper, not the viewport.</p>
</article>
</div>The .card-wrapper element is just the box the card sits in. In a real page it might be a grid cell, a sidebar widget, or a <li>.
What media queries measure
A media query tests the viewport (or the device, the print medium, or a user preference). A width condition such as min-width: 60rem is true or false for the whole page at once. Every element on the page sees the same answer.
A typical attempt at the card looks like this:
.card {
display: block;
}
@media (min-width: 60rem) {
.card {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
}This works when the card always fills the page width. It fails as soon as the layout puts the card in a narrow slot. On a 1200px-wide window the media query matches, so the sidebar card switches to the two-column layout. The sidebar is about 18rem wide, so the 8rem image column leaves roughly 10rem for text. The same viewport also makes the card in the main column look correct. One condition cannot be right for both.
Authors have worked around this in several ways, and each has costs:
- Modifier classes such as
.card--compactthat the page author applies by hand. These push layout knowledge into the markup, and they break when the layout changes. - Context selectors such as
.sidebar .card. These tie the component to every place it might be used, and the list grows with each new slot. - Viewport breakpoints tuned per page. These are fragile. Changing the sidebar width means revisiting every breakpoint that assumed it.
- JavaScript with
ResizeObserver. This works, but it moves layout logic out of CSS, runs after layout, and can cause a visible flash.
All of them exist because the component cannot ask its surroundings directly.
The shift: ask the container
A container query changes what the condition is tested against. Instead of the viewport, the condition measures an ancestor element that you have marked as a container. The component then adapts to the space it was actually given.
The diagram below shows the same card in two slots under one viewport width.
Here is the card rewritten with a container query. It is a preview, and the next chapters explain each line.
.card-wrapper {
container-type: inline-size;
container-name: card;
}
.card {
display: block;
}
@container card (min-width: 30rem) {
.card {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
}Read it in three parts:
.card-wrapperis declared as a query container.container-type: inline-sizetells the browser to track its inline size (its width, in horizontal writing modes).container-name: cardgives it a name so rules can target it on purpose.- The
@container card (min-width: 30rem)rule applies when that wrapper is at least 30rem wide. The viewport is irrelevant.
The 45rem main column matches, so its card is a two-column grid. The 18rem sidebar does not match, so its card stays stacked. You wrote the card once, and it needs no knowledge of the page.
Why the container must opt in
Why not let a component query its parent automatically? The answer is a circular dependency.
A parent's size often depends on its children. A block's height grows with its content, and a shrink-to-fit width depends on what is inside. If a child could change its own styles based on its parent's size, and those styles changed the child's size, the parent's size would change again, and the browser could loop forever.
The browser avoids this with containment. When you set container-type, the element promises that its size in the queried dimension does not depend on its contents. With inline-size, that dimension is the inline axis. The browser can then compute the container's width first, without looking at the children, and evaluate the queries against it.
This has two practical consequences that later chapters return to:
- Containment is a trade. You get a stable measurement, and in exchange the container's inline size can no longer come from its content. A container that used to shrink-wrap its children may collapse to zero width.
- Because the container's size is fixed before its children are laid out, a query cannot style the container itself. It can only style descendants. That is why the example above has a wrapper and a card, not one element.
The second point is the most common first mistake. If .card were both the container and the thing in the @container rule, the rule would never apply to it.
What a container can tell a component
The tutorial covers three kinds of information a component can read from its surroundings:
| Mechanism | What the component learns | Example use |
|---|---|---|
| `@container (min-width: ...)` | The container's size | Switch a card between stacked and side-by-side |
| Container query units (`cqi`, `cqw`, and others) | The container's size as a length | Scale padding and heading size with the wrapper |
| `@container style(--name: value)` | A custom property value on an ancestor | Apply a warning or brand variant to an alert |
Size conditions answer "which layout fits?" Units answer "how large should this be, proportionally?" Style queries answer "what context was I placed in?", which is a question about meaning rather than size. All three read from an ancestor, and the rules for choosing which ancestor are the same. The chapter on nearest-ancestor resolution covers them.
Media queries still have a job
Container queries do not replace media queries. They split the work along a clear line.
| Question | Use |
|---|---|
| How much space does this component have? | Container query |
| How is the overall page arranged (columns, navigation placement)? | Media query or container query on a layout wrapper |
| Does the user prefer reduced motion or a dark color scheme? | Media query (`prefers-reduced-motion`, `prefers-color-scheme`) |
| Is the page being printed, or is the pointer coarse? | Media query (`print`, `pointer`, `hover`) |
| What variant or theme applies here? | Style query or a class |
A good rule is to ask what the condition describes. If it describes the device or the user, it belongs in a media query. If it describes the space or context of one component, it belongs in a container query.
The two combine well. A page might use a media query to decide whether the sidebar appears beside the content or below it. Each card then uses a container query to adapt to whichever slot it landed in. The page layer answers for the viewport, and the component layer answers for its container.
Edge cases to keep in mind
- Containers are not free. Each container adds a containment boundary. Marking every element as a container makes layout harder to reason about and can cause the width collapse described above. Mark the wrappers that components actually need.
- Fixed-size slots still work. A container query on a wrapper that is always 20rem wide never changes. That is fine, but it is also a sign that a plain class would do.
- Nesting is allowed. A card inside a sidebar inside a page can sit inside several containers. By default a query matches the nearest ancestor that qualifies. Naming containers lets you target a specific one.
- Components that are also layout. If you want a layout wrapper to change its own columns based on its own width, query a parent container, or put the container on an outer wrapper. A wrapper cannot respond to itself.
- Support is broad but not universal. Size container queries and container units are supported in current evergreen browsers. Style queries on custom properties arrived in browsers on a different schedule than size queries. The final chapter shows how to ship these features with
@supportsand a sensible single-column default.
Where the tutorial goes next
The chapters build in this order:
- This chapter: why components should read their container.
- How to declare a container with
container-type. - How to write
@containersize queries. - Naming containers and the
containershorthand. - Container query units such as
cqi,cqb,cqw,cqh,cqmin, andcqmax. - Fluid type and spacing with
cqiandclamp(). - What container units resolve to when there is no container.
- How the nearest ancestor container is chosen.
- Style queries with
@container style(). - Variants and themes through custom property queries.
- Pitfalls: self-styling, inline-size collapse, and other containment effects.
- Browser support and progressive enhancement with
@supports.
Summary of the model
A media query asks about the page. A container query asks about a specific ancestor that has opted in with container-type. That opt-in lets the browser measure the container before laying out its contents, which avoids circular sizing but means the container cannot be styled by its own query. The result is a component that carries its responsive behavior with it, wherever it is placed.
Exercise
A card uses @media (min-width: 60rem) to switch to a two-column layout. On a 1400px-wide window, the card in an 18rem sidebar looks cramped, while the card in the main column looks fine. Explain why the media query cannot fix this, and name the change that would.
Show answer
A media query tests the viewport, and the viewport is 1400px wide for both cards, so the condition is true for both and both switch to two columns. The sidebar card does not have room for that layout, but the media query cannot see the sidebar's width. The fix is to make the card's wrapper a container (container-type: inline-size) and replace the media query with an @container (min-width: 30rem) rule. Each card then compares its own wrapper's width to 30rem, so the main column card gets two columns and the sidebar card stays stacked.
Exercise
A developer writes .card { container-type: inline-size; } and then @container (min-width: 30rem) { .card { display: grid; } }. The grid never applies, even though the card is 40rem wide. Give the cause and a fix.
Show answer
A container query only styles descendants of the container, never the container itself. Here .card is both the container and the styled element, so the rule cannot match it. The fix is to move container-type: inline-size to a wrapper element around the card (for example .card-wrapper) and keep the @container rule targeting .card.
Exercise
For each condition, say whether a media query or a container query is the better fit: (a) the user prefers reduced motion, (b) a product tile should hide its description when its slot is narrower than 15rem, (c) the page should print without the navigation.
Show answer
(a) Media query, because prefers-reduced-motion describes the user's preference. (b) Container query, because the condition describes the space available to one component. (c) Media query, because print describes the output medium.