Sub topic 4
Writing your first @container rule
This chapter assumes you know the following:
- Core CSS: selectors, the cascade, and the box model.
- Basic flexbox or grid layout.
@mediaqueries.- The
container-typeproperty from the previous chapter.
Here you will write a working @container rule, learn how the browser evaluates it, and see the mistakes that stop it from applying.
The shape of an @container rule
An @container rule is an at-rule, like @media. It has a condition in parentheses and a block of ordinary style rules inside. Those rules apply only while the condition is true for a query container.
@container (min-width: 400px) {
.card {
grid-template-columns: 8rem 1fr;
}
}The rule has three parts:
- The keyword
@container. - A condition, here
(min-width: 400px). - A block of style rules. Their selectors target elements that are descendants of the container.
The difference from @media is what the condition measures. A media query reads the viewport. A container query reads the size of an ancestor element that you have declared as a container.
A complete first example
Start with the markup. The wrapper is the container. The card is the component inside it.
<div class="card-wrapper">
<article class="card">
<div class="thumb"></div>
<div class="body">
<h2>Container queries</h2>
<p>This card reacts to the width of its wrapper, not the window.</p>
</div>
</article>
</div>Now the CSS:
.card-wrapper {
container-type: inline-size;
}
.card {
display: grid;
gap: 1rem;
}
.thumb {
min-height: 6rem;
background: #8ab;
}
@container (min-width: 400px) {
.card {
grid-template-columns: 8rem 1fr;
}
}By default, the card is a single column with the thumbnail stacked above the text. When .card-wrapper is at least 400px wide, the card becomes two columns. The viewport size does not matter. Put the same markup in a 300px sidebar on a wide monitor and it stays stacked. Put it in a 600px main column on a small laptop and it becomes two columns.
The declaration container-type: inline-size is what makes .card-wrapper a query container. Without it, the @container rule has nothing to measure and never applies.
How the browser evaluates the rule
For every element matched by a selector inside an @container block, the browser does these steps:
- It walks up the ancestors to find the nearest query container that can answer the condition.
- It reads that container's current size.
- If the condition is true, the rules in the block apply. If not, they are ignored.
- If the container resizes, the browser re-evaluates the condition and updates the styles.
Because the result depends on a container's size and the container's size depends on layout, the browser evaluates container queries during layout, not before it. You do not need to manage this yourself. It does explain the first rule below.
Rules that surprise people
The container cannot style itself
The styles inside an @container block apply to descendants of the container. They never apply to the container element itself. This is a deliberate limit. If an element could change its own size in response to its own size, the result could loop forever.
This rule does nothing:
.card-wrapper {
container-type: inline-size;
}
@container (min-width: 400px) {
.card-wrapper {
padding: 2rem;
}
}The selector .card-wrapper matches the container, not a descendant, so the browser never applies it from its own query. The fix is to add a wrapper element whose only job is to be the container, and style what is inside it. This is why the example uses .card-wrapper and .card as separate elements.
The width is the content box
The condition measures the container's content box. That is the area inside its padding and border. If .card-wrapper is 420px wide with padding: 1rem (16px each side), the queried width is 388px. The condition (min-width: 400px) is false even though the element looks wider than 400px.
If a query flips at a size you did not expect, check the container's padding and border first.
Inline size, not always "width"
container-type: inline-size makes the container report its size along the inline axis. In the usual horizontal writing modes, such as English, that axis is horizontal, so it matches width. In a vertical writing mode, the inline axis is vertical. The width feature in a query always refers to the physical width. Querying it on an inline-size container in a vertical writing mode may therefore not behave as you expect. For most pages in horizontal text, inline-size and width are the same thing.
The container must be able to be a container
container-type only works on elements where size containment can apply. An element with display: inline cannot be a query container, so the declaration has no effect and the queries find nothing. Block, flex, grid, and inline-block elements work.
Where @container can appear
An @container rule is a conditional group rule. You can use it in these places:
- At the top level of a stylesheet, as in the examples above.
- Inside another
@container,@media, or@supportsblock. - Nested inside a style rule when you use CSS nesting.
With nesting, the inner rule's selector is relative to the parent:
.card {
display: grid;
gap: 1rem;
@container (min-width: 400px) {
grid-template-columns: 8rem 1fr;
}
}Here .card is a descendant of the container, so the rule works. Nested @container rules can read well because the component's base styles and variations sit together.
You can also combine @media and @container. Use @media for page-level concerns such as prefers-reduced-motion or the overall layout. Use @container for how a component arranges itself.
@media (prefers-reduced-motion: no-preference) {
@container (min-width: 400px) {
.card {
transition: grid-template-columns 0.2s;
}
}
}Which container does the query read?
When you write an unnamed query, the browser picks the nearest ancestor that is a query container and supports the feature in your condition. "Nearest" means closest up the tree, not the one that appears first in the stylesheet.
<div class="outer">
<div class="inner">
<div class="item">Item</div>
</div>
</div>.outer,
.inner {
container-type: inline-size;
}
@container (min-width: 300px) {
.item {
color: green;
}
}The .item element reads .inner, because .inner is its closest ancestor container. The width of .outer is ignored. If you need to target a farther ancestor, you must name the containers. That is the subject of a later chapter. For now, keep one container in the ancestor chain of each component so that the answer is obvious.
Testing the example
Save the markup and CSS in one page. Then try these changes, one at a time, in your browser:
- Wrap
.card-wrapperin adivwithwidth: 300pxand reload. The card is stacked. - Change that width to
500px. The card becomes two columns. - Keep the wrapper at 500px and add
padding: 5remto.card-wrapper. The content box is now about 340px, so the card stacks again. - Remove
container-type: inline-size. The card stays stacked at every width, because the query has no container.
The last two tests reproduce the most common reasons a first query seems broken.
First-rule checklist
If your @container rule does not apply, check these in order:
| Check | What to look for |
|---|---|
| Is there a container? | An ancestor of the styled element has `container-type` set. |
| Is it an ancestor? | The styled element is inside the container, not the container itself. |
| Can the element be a container? | It is not `display: inline`. |
| Which container is nearest? | A closer container may be reporting a smaller width. |
| Is the width the content box? | Padding and border are subtracted from the measured width. |
| Does the condition use a valid feature? | `width`, `inline-size`, and so on. A typo makes the whole condition false. |
| Is the selector specific enough? | A later or more specific rule outside the `@container` block can still win. |
Remember that @container adds a condition, not specificity. A rule inside the block has the same specificity as it would outside. If a more specific selector sets the same property elsewhere, that selector wins even when the container condition is true.
Exercise
A page contains <div class="box"><p class="text">Hello</p></div>. The CSS is .box { container-type: inline-size; } @container (min-width: 500px) { .box { background: gold; } }. The .box element is 800px wide, but its background never turns gold. Why, and how would you fix it?
Show answer
The rule inside @container targets .box, which is the container itself. A container query only applies to descendants of the container, so it never matches .box. To fix it, style a descendant such as .text, or add an outer wrapper that becomes the container and keep .box as the element being styled.
Exercise
.panel has container-type: inline-size, a width of 420px, and padding: 1rem (16px per side, with box-sizing: border-box). A descendant has a rule inside @container (min-width: 400px). Does the rule apply? Explain.
Show answer
No. With box-sizing: border-box, the content box is 420px minus 32px of padding, which is 388px. Container queries measure the content box, so 388px is less than 400px and the condition is false.