Sub topic 2
Declaring a Container with container-type
A container query asks a question about an ancestor element instead of the viewport. Before any @container rule can work, the browser has to know which ancestor to ask. You tell it by declaring that element a query container with the container-type property.
This chapter assumes you are comfortable with selectors and the cascade, media queries and viewport units, flexbox or grid basics, and CSS custom properties. Naming containers, writing size conditions, and container units each get their own chapter. Here the focus is the declaration and what it costs you.
Why a declaration is needed
A media query is cheap to evaluate because the viewport size does not depend on the page content. An element's size usually does depend on its content. If a card could change its own layout based on its own width, a layout change could change the content, which could change the width, and so on. That is a circular dependency.
Browsers avoid the cycle by requiring you to opt in. When you set container-type on an element, you promise that the element's size will not depend on its descendants, at least along the axes you named. The browser enforces that promise with CSS containment. Once the size is independent of the content, descendants can safely query it.
The three values
container-type accepts three values.
| Value | Effect | Queryable by size |
|---|---|---|
| `normal` | The default. No size containment. The element can still be queried by style queries. | No |
| `inline-size` | Inline-size containment. The element is a size container on its inline axis only. | Width in horizontal writing modes |
| `size` | Size containment on both axes. | Inline and block dimensions |
The inline axis is the direction text runs. In English and other horizontal writing modes it is the horizontal axis, so inline-size behaves like width. In a vertical writing mode such as writing-mode: vertical-rl, the inline axis is vertical. That is why the property and the related units are named with "inline" and "block" instead of "width" and "height".
In practice you will use inline-size almost every time. Components usually grow downward with their content, so you want height to stay content-driven. Use size only when the container has a height that comes from somewhere else, such as an explicit height or a grid track.
A first working example
The markup separates the container from the element it styles. The wrapper is the container and the article is a descendant.
<div class="card-wrapper">
<article class="card">
<h2>Title</h2>
<p>Body text that reflows with the wrapper, not the viewport.</p>
</article>
</div>.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;
}
}The wrapper is now a named inline-size container. When the wrapper is at least 30rem wide, .card switches to a two-column grid. The viewport can be 400px or 2000px wide. Only the wrapper's width matters. If you place the same markup in a narrow sidebar and in a wide main column, each copy picks its own layout.
A container cannot style itself
A container query matches against an ancestor of the element being styled. It never matches against the element itself. A rule inside @container can only style the container's descendants.
This surprises people the first time. The following rule does nothing, because the selector targets the container itself:
.card-wrapper {
container-type: inline-size;
}
@container (min-width: 30rem) {
.card-wrapper {
padding: 2rem; /* never applies: the wrapper is the container */
}
}The fix is structural. Add a wrapper element or move the container-type up one level so the element you want to style becomes a descendant. This is the reason component libraries often have an extra wrapper div.
What the declaration costs
Setting container-type to inline-size or size applies several kinds of CSS containment to the element. Each one has a visible side effect.
Layout containment
Layout containment makes the container independent of the rest of the page for layout purposes. These effects follow from it:
- The container becomes the containing block for absolutely and fixed-positioned descendants, even if it has
position: static. Aposition: fixedchild will position relative to the container, not the viewport. - The container creates a new stacking context, so
z-indexvalues inside it no longer compete with elements outside it. - The container establishes an independent formatting context. Margins of children do not collapse through it, and floats inside do not escape.
If a dropdown or tooltip suddenly appears in the wrong place or is clipped after you add a container, check this list first.
Style containment
Style containment scopes some features, such as CSS counters and quotes, to the container's subtree. A counter incremented inside the container does not continue outside it. Custom properties are not affected, so inheritance of --name values works as normal.
Inline-size containment
With inline-size, the container's inline size is computed as if it had no content. The container's width comes only from its context and its own properties: width, flex, a grid track, or simply filling the parent. Its block size still depends on the content as usual.
Size containment
With size, both axes are computed as if the element were empty. A container with container-type: size and no explicit height collapses to zero height, even if it holds paragraphs.
Collapse in shrink-to-fit contexts
Inline-size containment is harmless for a block-level element in normal flow, because it fills its parent. It is a problem wherever the width would normally come from the content (shrink-to-fit): flex items with flex-basis: auto, grid items in auto tracks, floats, inline-block elements, and absolutely positioned boxes without a width.
This example puts the container in a flex row, which is a common setup:
<div class="toolbar">
<div class="card-wrapper">
<article class="card">
<h2>Title</h2>
<p>This text has nowhere to stretch.</p>
</article>
</div>
<aside class="side">Side content</aside>
</div>.toolbar {
display: flex;
gap: 1rem;
}
.card-wrapper {
container-type: inline-size;
/* Without this line the wrapper's content-based width is 0 */
flex: 1 1 20rem;
}
.card {
padding: 1rem;
border: 1px solid #ccc;
}
@container (min-width: 30rem) {
.card {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
}If you remove the flex line, the wrapper's content size is treated as zero, so it shrinks to nothing and the text wraps one character at a time. The cure is to give the container a width from outside: flex: 1, width: 100%, a grid-template-columns track like minmax(0, 1fr), or min-width.
Choosing between inline-size and size
Use this as a decision rule:
- Choose
inline-sizewhen the component's height grows with its content. This covers cards, sidebars, form groups, and article bodies. - Choose
sizeonly when you need to query the block dimension, and the container has a height that is set from outside, such asheight: 100%inside a sized parent or a fixed grid row.
With size, always set the height yourself. Otherwise, you query a box that has collapsed to zero.
Querying the block axis is also less portable in practice. Many layouts let height follow content, so inline-size fits most of them.
Which elements can be containers
Almost any element that generates a box can be a container. Two exceptions matter:
- An element with
display: nonegenerates no box, so it cannot be queried. An element withdisplay: contentsgenerates no box of its own, so it cannot be a size container either. - Internal table elements (such as
trandtd) and internal ruby elements cannot be size containers. Wrap the content in adivinstead.
Setting display: inline on a container is also a trap. An inline box has no inline size to query, so use a block-level, flex, or grid display for the container.
Checking your work
When a query does not seem to apply, work through this list:
- Is
container-typeset on an ancestor, and not on the element you are styling? - Is the container's width non-zero? Inspect it in your browser's developer tools. Many browsers mark containers with a badge in the elements panel.
- If you used a name, does the
@containername match exactly? Names are case-sensitive. - Is the condition against the right axis?
min-widthon asizeorinline-sizecontainer tests the container's inline size when the writing mode is horizontal.
Exercise
A developer writes .panel { container-type: inline-size; } and then @container (min-width: 40rem) { .panel { padding: 2rem; } }. The padding never changes, even when .panel is 60rem wide. Why, and how do you fix it?
Show answer
A container query only matches against an ancestor of the element being styled, so the rule cannot style .panel, which is the container itself. Wrap the panel's content in a child element, or move container-type to a parent wrapper, and apply the padding to a descendant of the container.
Exercise
A container with container-type: size holds three paragraphs of text and has no height set. What height does it have, and what would you change?
Show answer
Size containment makes the element's block size be computed as if it had no content, so it collapses to zero height (plus any padding and border). Either give it an explicit height from outside, or switch to container-type: inline-size if you only need to query width.
Exercise
You put container-type: inline-size on a flex item, and the item shrinks to almost nothing. Name two ways to fix it.
Show answer
Inline-size containment removes the content-based width, so the item needs a width from another source. Possible fixes include flex: 1 1 20rem (or any flex value with a basis), width: 100%, or a min-width.