Sub topic 15
When to use container queries instead
This chapter assumes you can write @media rules with min-width, build a grid with grid-template-columns, and use em and rem units. It covers the cases where a media query measures the wrong thing, and how a container query fixes them.
The problem with viewport-based queries
A media query asks about the viewport, the visible area of the browser window. That works for page-level decisions such as whether the sidebar sits beside the content or below it. It works badly for components, because a component's available space is not the same as the viewport width.
Take a .card component. On a wide screen you might place it in a three-column grid, in a narrow sidebar, and in a full-width main area. The viewport is 1400px in all three cases, but the card has about 380px, 260px and 1100px to work with. A media query cannot tell these apart, so you end up writing overrides like .sidebar .card { ... } for each place the card appears.
A container query measures the nearest ancestor you mark as a container. The card adapts to the space it was given, wherever it is placed.
The basic mechanism
Two steps are needed. First, mark an ancestor as a container. Second, write an @container rule that styles its descendants.
<!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>
.card-wrapper {
container-type: inline-size;
}
.card {
padding: 1rem;
border: 1px solid #999;
}
@container (min-width: 30em) {
.card {
display: flex;
gap: 1rem;
}
}
</style>
</head>
<body>
<div class="card-wrapper">
<article class="card">
<h2>Title</h2>
<p>Card text that sits beside the heading once the wrapper is wide enough.</p>
</article>
</div>
</body>
</html>container-type: inline-size tells the browser to track the wrapper's width (the inline axis in horizontal writing modes). Below 30em of wrapper width the card stacks. At 30em and above it becomes a flex row.
Three rules to remember:
- A container query can only style descendants of the container. It cannot restyle the container itself, which would create a loop: the query changes the size, and the size decides the query.
- The query matches against the nearest ancestor that has a container type, unless you name containers (see below).
@containeraccepts the same range syntax as media queries, for example@container (400px <= width <= 700px).
Naming containers
When containers nest, the nearest one wins. To target a specific ancestor, give it a name. The shorthand sets the name and the type together.
.page-main {
container: main-area / inline-size;
}
.card-wrapper {
container: card-area / inline-size;
}
@container main-area (min-width: 60em) {
.featured {
font-size: 1.25rem;
}
}
@container card-area (min-width: 30em) {
.card {
display: flex;
gap: 1rem;
}
}Without names, both rules would match against .card-wrapper, because it is the nearest container to everything inside it. Names make each query refer to the intended ancestor.
Container-relative units
Container queries come with length units based on the container's size. 1cqi is 1% of the container's inline size, and 1cqw is 1% of its width. They work like vw, but relative to the container.
.card-title {
font-size: clamp(1.1rem, 4cqi, 1.75rem);
}This title scales with the card's width. It does not scale with the window, so the same card is sized sensibly in a narrow sidebar and in a wide main column.
Decision criteria
Use this table to choose between the two kinds of query.
| Question | Use a media query | Use a container query |
|---|---|---|
| What decides the layout change? | Viewport size or a device trait | The space given to one component |
| Is the component reused in different-width slots? | No | Yes |
| Is the change page-level (header, navigation, overall grid)? | Yes | Rarely |
| Does it depend on user settings such as dark mode or reduced motion? | Yes | No |
| Does it depend on input type (`hover`, `pointer`) or print? | Yes | No |
A common pattern combines both. Media queries set the page skeleton, such as how many columns the page has. Container queries handle the components inside those columns.
Gotchas and failure modes
Size containment can collapse the container
container-type: inline-size applies inline-size containment. The browser then computes the container's width without looking at its contents. If the container's width depends on its contents, it can shrink to nothing. Elements sized this way include:
- floated elements
display: inline-blockelements- flex or grid items with
width: autoinside a shrink-to-fit track - absolutely positioned elements without a set width
In practice, containers should be block-level elements that fill their parent, such as a div in normal flow or a grid cell. If a container disappears, check how its width is determined.
You cannot query the container's height by default
inline-size tracks only the inline axis. Querying height needs container-type: size, which contains both axes. You must then give the container an explicit height, or it collapses to zero in the block direction. Most layouts need only width, so prefer inline-size.
An extra wrapper is often needed
Because the container cannot style itself in its own query, you often need a wrapper element around the component. The component's root element is then the first descendant that can change. If your .card is itself the container, a query cannot restyle .card, only things inside it.
Container queries do not replace the viewport meta tag
Container queries depend on correct layout widths. On mobile browsers without <meta name="viewport" content="width=device-width, initial-scale=1">, the page is laid out at about 980px and scaled down. Your containers are then measured at that wider layout, and the results look wrong.
Container queries cannot read user preferences
A container query measures size (and, with style queries, custom property values). It has no access to prefers-color-scheme, prefers-reduced-motion, hover, pointer or print. Those stay in media queries. You can nest an @container rule inside an @media rule, or the reverse, when a style depends on both.
@media (hover: hover) and (pointer: fine) {
@container (min-width: 30em) {
.card:hover {
background: #f0f4ff;
}
}
}Browser support
Size container queries are supported in current versions of Chrome, Edge, Safari and Firefox. If you must support older browsers, write the narrow-container layout as the default and treat the @container rule as an enhancement. Older browsers then show the stacked layout, which still works.
Testing container queries
Browser developer tools help here. In Chrome and Edge, elements that are containers show a container badge in the Elements panel, and clicking it highlights the container. In Firefox, the Inspector shows a similar badge. Resize the slot, not the window: drag the sidebar width, or change the parent grid's column count, and watch the component change. Also place the same component in two differently sized slots on one test page, because that is the case container queries exist for.
Exercise
A .product component is used in a main column (about 900px wide) and in a sidebar (about 280px wide) on the same page. You write @media (min-width: 40em) { .product { display: flex; } } and the sidebar product looks cramped on wide screens. What change fixes this, and what must the wrapper around .product have?
Show answer
Replace the media query with a container query: @container (min-width: 30em) { .product { display: flex; } }. Give the wrapper around .product (not .product itself) container-type: inline-size, optionally with a name. The query then measures each wrapper's own width, so the 280px sidebar stays stacked while the 900px column gets the flex layout. The wrapper should be a block-level element that fills its slot, so size containment does not collapse it.
Exercise
Which of these should stay a media query: (a) switching to a dark palette, (b) turning a card into a two-column layout, (c) hiding the navigation when printing?
Show answer
(a) and (c). Dark mode is a user preference (prefers-color-scheme) and printing is a media type. Container queries cannot read either. Item (b) depends on the space given to the card, so it is a container query case if the card is reused in slots of different widths.