Sub topic 11
Container queries for reusable components
This chapter assumes you have read the earlier chapters on base styles, min-width media queries and fluid layouts with Grid. You should be comfortable writing a @media (min-width: ...) rule and reading a Grid declaration.
The problem media queries cannot solve
Media queries measure the viewport. That works for page-level decisions, such as whether the page has one column or two. It fails for components.
Suppose you build a product card. On a wide screen you place it in a main column that is 700px wide, and it should show an image beside the text. You also place the same card in a 280px sidebar on that same wide screen. A min-width media query sees one viewport width for both placements, so both cards get the same layout. One of them will look wrong.
A container query asks a different question: how wide is the box this component sits in? The component then adapts to its own space, wherever you put it.
The working model
A container query has two parts. You declare an element as a query container, and you write rules that apply when that container meets a size condition.
.card-list {
container-type: inline-size;
}
.card {
display: block;
}
@container (min-width: 40rem) {
.card {
display: flex;
gap: 1rem;
}
}Here .card-list is the container. Its inline-size is its width in horizontal writing modes. The @container rule applies to any descendant of the container, and it measures the nearest ancestor that qualifies as a container.
The mobile-first pattern still holds. The base .card rule is the stacked, narrow layout. The min-width container query adds the horizontal layout only when there is room, which is the same "add, don't undo" approach you used with media queries.
The container cannot style itself
A container query can only style descendants of the container. A rule inside @container that targets the container element itself has no effect. This is the most common mistake.
/* Wrong: the query container is also the element being styled */
.card {
container-type: inline-size;
}
@container (min-width: 40rem) {
.card {
display: flex; /* never applies to .card itself */
}
}The fix is a wrapper. Put container-type on the wrapper and style the child. In practice, many component libraries add a wrapping element for this reason.
What `container-type` does to layout
Setting container-type: inline-size applies containment on the inline axis. The browser must be able to compute the container's width without looking at its contents. Otherwise the query could change the contents, which would change the width, which would change the query result, and the layout could loop forever.
This has practical effects:
- A block-level container with
inline-sizeusually fills the available width, so it works naturally. - An inline-level or shrink-to-fit container, such as a flex item with no set width, may collapse to zero width because its contents no longer contribute to its size. Give it a width,
flex: 1, or a Grid track. - Block-direction (height) queries need
container-type: size. That requires you to set the height explicitly, so you rarely use it.
| Value | What you can query | Cost |
|---|---|---|
| `normal` | Nothing for size (style queries only) | None |
| `inline-size` | Width in horizontal writing modes | Width must not depend on contents |
| `size` | Width and height | Both dimensions must not depend on contents |
Naming containers
An unnamed query matches the nearest container ancestor. When components nest, that may not be the one you meant. Give containers names and target them explicitly.
.sidebar {
container-name: sidebar;
container-type: inline-size;
}
.page {
container: page / inline-size; /* shorthand: name / type */
}
@container sidebar (max-width: 20rem) {
.widget {
font-size: 0.875rem;
}
}
@container page (min-width: 60rem) {
.promo {
display: grid;
grid-template-columns: 2fr 1fr;
}
}The container shorthand takes the name, a slash, then the type. A name also makes your intent obvious to readers, because the query states which box it measures.
A complete runnable example
This page shows the same card in a wide main column and a narrow sidebar. Save it and open it in a browser. Resize the window to see that the two cards choose different layouts at the same viewport width.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Container query demo</title>
<style>
body { font-family: system-ui, sans-serif; margin: 0; padding: 1rem; }
.page {
display: grid;
gap: 1rem;
}
@media (min-width: 48em) {
.page { grid-template-columns: 2fr 1fr; }
}
.slot {
container-type: inline-size;
}
.card {
display: grid;
gap: 0.75rem;
padding: 1rem;
border: 1px solid #b8c2d6;
border-radius: 0.5rem;
}
.card-media {
min-block-size: 6rem;
background: #dbe4fb;
border-radius: 0.25rem;
}
@container (min-width: 28rem) {
.card {
grid-template-columns: 10rem 1fr;
align-items: start;
}
}
</style>
</head>
<body>
<div class="page">
<main class="slot">
<article class="card">
<div class="card-media"></div>
<div>
<h2>Main column card</h2>
<p>This card has room, so the image sits beside the text.</p>
</div>
</article>
</main>
<aside class="slot">
<article class="card">
<div class="card-media"></div>
<div>
<h2>Sidebar card</h2>
<p>Same markup, stacked layout.</p>
</div>
</article>
</aside>
</div>
</body>
</html>Notice the division of labor. A media query decides the page's two-column layout. A container query decides the card's internal layout. Each tool handles the level it can measure.
Container query units
Inside a container, you can size things relative to the container with query length units. The most useful is cqi, 1% of the container's inline size.
.slot {
container-type: inline-size;
}
.card h2 {
font-size: clamp(1.125rem, 4cqi, 1.75rem);
}This heading scales with its container and stays between 1.125rem and 1.75rem, using the clamp() technique from the typography chapter. If no ancestor is a query container, these units fall back to the small viewport units, so they never break outright.
Choosing between media and container queries
| Question | Use |
|---|---|
| Does the overall page structure change? | Media query |
| Does a component's layout depend on where it is placed? | Container query |
| Does the user's device or setting matter (hover, reduced motion, color scheme)? | Media query |
| Is the component reused in several differently sized slots? | Container query |
User preference and input capability features, such as prefers-reduced-motion and hover, describe the device or user. A container has no such features, so those stay as media queries.
Edge cases and gotchas
- Support and fallback. Container size queries are supported in current evergreen browsers. For older browsers, the stacked base layout is what they get, so the mobile-first approach degrades gracefully. You usually do not need
@supports. If you want to detect support, use@supports (container-type: inline-size). - Padding and borders. The query measures the container's content box by default. Padding on the container reduces the width the query sees. Test with real padding.
- Do not make everything a container. Each container adds containment work for the browser. Mark containers at meaningful component boundaries, not on every
div. - Avoid querying wrappers you resize. If a container's width depends on a child that a query resizes, you will see collapse rather than a loop, because containment prevents the loop. Give containers an explicit or layout-driven width.
- Breakpoints still come from content. Choose the container query threshold where the component starts to look cramped, not from a device size. Express it in
remoremso it follows the user's font size.
Summary of the process
- Write the component's base styles for the narrowest case.
- Add a wrapper or ancestor with
container-type: inline-size, and name it if components nest. - Add
@container (min-width: ...)rules that enhance the layout when space allows. - Place the component in a narrow and a wide slot and confirm that each adapts independently.
Exercise
A developer sets container-type: inline-size on .promo and writes @container (min-width: 30rem) { .promo { display: grid; grid-template-columns: 1fr 1fr; } }. The grid never applies, even when .promo is 50rem wide. What is wrong, and how do you fix it?
Show answer
The rule targets the container itself, and a container query can only style descendants of the container. Wrap the content in a container element (for example, put container-type: inline-size on a wrapper around .promo) and keep the @container rule on .promo. Alternatively, keep .promo as the container and apply the grid to a child element such as .promo-inner.
Exercise
Why can a media query not tell a card in a 280px sidebar apart from the same card in a 700px main column on a 1200px-wide viewport, and which feature can?
Show answer
A media query measures the viewport, which is 1200px for both placements, so both cards match the same rules. A container query measures the nearest query container, so the sidebar slot (280px) and the main slot (700px) produce different results for the same component.