Sub topic 13
Container Queries for Component-Level Breakpoints
This chapter assumes you can write mobile-first CSS with min-width media queries, use CSS Grid, and read the breakpoint tokens and frames set up in earlier chapters. It covers a limit of viewport breakpoints and the CSS feature that removes it.
Why viewport breakpoints are not enough
A media query asks about the viewport. That works for page-level decisions such as how many columns the page has or whether the navigation collapses. It fails for components that appear in several places.
Take a product card. On a wide screen it sits in the main column, about 700px wide. In the same layout it also appears in a 280px sidebar. The viewport is 1400px in both cases, so a min-width: 80em rule gives both cards the same layout. The sidebar card gets squeezed.
You can work around this with modifier classes such as .card--compact, set by hand wherever the card is placed. That moves layout logic into the markup and breaks when the layout changes. Container queries move the decision into the component. The card looks at the space it was given and adapts.
The working model
A container query has two parts:
- Declare a container. An ancestor element opts in with
container-type. The browser then tracks that element's size. - Query it. An
@containerrule applies styles to descendants of that container when its size meets a condition.
<!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>
.page {
display: grid;
gap: 1rem;
padding: 1rem;
}
@media (min-width: 48em) {
.page { grid-template-columns: 2fr 1fr; }
}
.card-list {
container-type: inline-size;
}
.card {
display: grid;
gap: 0.5rem;
padding: 1rem;
border: 1px solid #ccd;
border-radius: 0.5rem;
}
.card img {
width: 100%;
height: auto;
}
@container (min-width: 30rem) {
.card {
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
}
</style>
</head>
<body>
<div class="page">
<main class="card-list">
<article class="card">
<img src="https://placehold.co/320x200" alt="Placeholder product photo">
<div>
<h2>Trail jacket</h2>
<p>Light, packable, and water resistant.</p>
</div>
</article>
</main>
<aside class="card-list">
<article class="card">
<img src="https://placehold.co/320x200" alt="Placeholder product photo">
<div>
<h2>Trail jacket</h2>
<p>Light, packable, and water resistant.</p>
</div>
</article>
</aside>
</div>
</body>
</html>The page-level layout still uses a media query. The two cards use identical CSS. The one in <main> becomes two columns once its container reaches 30rem, and the one in <aside> stays stacked. Neither card knows or cares about the viewport.
What `container-type` does
container-type: inline-size makes the element a container for queries on its inline axis. In horizontal writing modes that is its width. This is the value to use almost every time. The other values are:
| Value | Effect |
|---|---|
| `normal` | Not a size container. The default. Style queries are still possible. |
| `inline-size` | Queries on the inline dimension (width in horizontal text). |
| `size` | Queries on both width and height. Requires the element's height to be set from outside. |
Declaring a size container applies containment. The element's size can no longer depend on its contents along the contained axis. That has consequences:
- A container whose width came from its children, such as a floated element or an inline-level flex item with no explicit width, may collapse to zero width. Give it a width from the layout: a grid track, a block-level width, or
flex: 1. - With
size, the same applies to height. Use it only when the height is set explicitly. - The container cannot restyle itself with its own query. The
@containerrule affects only descendants. This is why the example putscontainer-typeon.card-listand styles.card.
Naming containers
A query matches the nearest ancestor container by default. With nested containers, that may not be the one you meant. Give containers names and target them:
.sidebar {
container-name: sidebar;
container-type: inline-size;
}
/* Shorthand: name / type */
.main {
container: main / inline-size;
}
@container sidebar (max-width: 20rem) {
.widget-title {
font-size: 1rem;
}
}Names also keep a component's query working when someone later wraps it in another container.
Range syntax and container units
Modern browsers accept the range syntax inside @container, the same as in media queries:
@container (width >= 30rem) {
.card { grid-template-columns: 8rem 1fr; }
}
@container (20rem <= width < 40rem) {
.card h2 { font-size: 1.125rem; }
}The older min-width and max-width forms are equivalent. Pick one style and keep it throughout your code.
Inside a container you can also size things relative to the container with container query units:
| Unit | Meaning |
|---|---|
| `cqw` | 1% of the container's width |
| `cqh` | 1% of the container's height |
| `cqi` | 1% of the container's inline size |
| `cqb` | 1% of the container's block size |
These work like vw and vh, but relative to the nearest container instead of the viewport. They allow fluid type inside a component:
.card-list {
container-type: inline-size;
}
.card h2 {
font-size: clamp(1rem, 4cqi, 1.75rem);
}If no ancestor is a suitable container, the units fall back to the small viewport units. A component that looks right in one context and wrong in another often has a missing container-type.
Choosing between media and container queries
The two features answer different questions, so they are not competitors.
| Question | Use |
|---|---|
| How many columns does the page have? | Media query |
| Does the main navigation collapse into a menu? | Media query |
| Does this card put its image beside the text? | Container query |
| Does this widget show a short or long label? | Container query |
| Does the device support hover? | Media query (`hover`, `pointer`) |
| Is the user on a small screen with larger touch targets? | Media query |
A workable rule is that page structure follows the viewport and component internals follow their container. Page-level breakpoints stay in your design tokens and map to your tablet and desktop frames. Component breakpoints are local to the component and are usually written in rem.
Designing components in frames
Container queries change how you set up the design file as well as the CSS. A component that adapts to its container needs a frame per state, and those frames are sized by the component's width, not by a device.
- Build the component in a stacked state (narrow, around 280 to 320px) and an expanded state (wide, around 500 to 700px).
- Name the switch point after the content: "image moves beside text at 30rem". Record it next to the component, not in the global breakpoint tokens.
- In the page frames, show the same component in each place it appears, so reviewers can see that the sidebar instance and the main-area instance differ for a reason.
Choose a component's switch point the way you choose page breakpoints: resize the container until the content looks wrong, and put the breakpoint there.
Common errors
- Nothing happens. The element you are styling is the container itself, or no ancestor has
container-type. Move the declaration to a parent. - The container collapses. Containment removed its content-based width. Give it a width from the layout.
- The wrong container matches. Nested containers. Add
container-nameand use@container name (...). - A condition depends on the content's own size. A container query cannot respond to a child changing the container's size. The browser avoids that feedback loop by containing the size in the first place.
- Breakpoints in the wrong unit. A
pxcondition ignores the user's font-size setting. Useremorem.
Testing
Test a component in isolation by placing it in containers of several widths, such as 240, 320, 480, and 720px, with the viewport held fixed. Then test the whole page at a range of viewport widths. A component can look right in each of its states and still be wrong at the width where the page layout moves it from a wide area to a narrow one.
Exercise
A .promo component is inside a <section> that is 600px wide on a 1400px viewport. You write .promo { container-type: inline-size; } and @container (min-width: 30rem) { .promo { flex-direction: row; } }, but the row layout never applies. What is wrong, and how do you fix it?
Show answer
The .promo element is both the container and the element being styled, and an @container rule only affects descendants of the container. Wrap the content in a parent that declares container-type: inline-size (for example .promo-wrap), and apply the flex-direction: row rule to .promo inside it. Also check that the container has a width from the layout, so containment does not collapse it.
Exercise
Your design file has a sidebar frame at 280px and a main area frame at 700px, both showing a card. At what width should the card's layout switch, and where should that value be recorded?
Show answer
Switch the layout at the container width where the content starts to look wrong when stacked, found by resizing the component, for example 30rem. Record it with the component (in its container query and in the component's frame notes), not in the global page breakpoint tokens, because it depends on the component's content and not on the viewport.