Educational guide to @container
Adapt a component to its container
The same card can need one or two columns depending on where it is placed. Learn which box CSS queries, how it measures it and how to keep a working base layout when the condition does not apply.
Mental model
For each element matched by the selector, @container looks up the tree. It picks the nearest eligible ancestor and evaluates the condition against it. If the condition is false, the base style still applies even if a farther ancestor is above the threshold.
- Ancestor
The outer box accepts the query on the required axis. A name can narrow the search.
- Condition
The rule compares a measurement of that box with the threshold. The example queries its inline size.
- Descendant
The selector targets the inner card. Its new columns do not determine the ancestor’s contained size.
One card, two containers
Comparisons
Use @media for changes that depend on the viewport or environment, such as the page layout or a motion preference. Use @container when you want to reuse the same component in spaces of different sizes.
The same card in two spaces
Both groups live in the same iframe. If you have room, resize the window so the example’s viewport crosses 480 px.
Content box and axes
A size query measures the content box, excluding padding, border and margin. With width: 320px, box-sizing: border-box and 16px of padding on each side, with no border, the queried width is 288px.
width and height follow the physical axes. inline-size and block-size follow the container’s writing-mode. In horizontal-tb, inline-size corresponds to width. In vertical-rl, it corresponds to height. aspect-ratio compares width/height and orientation compares both physical dimensions. For those two queries, use a container eligible on both axes.
For dimensions, you can use (inline-size) to test for a nonzero value, (min-inline-size: 320px) to include the boundary, or (240px <= inline-size < 480px) to include only the lower bound. orientation takes keywords such as (orientation: portrait), which also matches a square box.
Size containment
container-type: inline-size keeps the contents from determining the container’s inline size. The block can still grow with its contents. container-type: size isolates sizing on both axes. Give it space through layout, for example with an explicit block-size or a grid track of a definite size. With an automatic block size and no space assigned, the box can collapse even if its children overflow.
The 2022 CSS Containment Level 3 draft included layout containment as an effect of inline-size and size. In July 2024, the CSSWG resolved that both types establish an independent formatting context without implying contain: layout. CSS Conditional Rules Level 5 reflects that change and retains style containment and size containment on the relevant axes.
Container names and units
container: card / inline-size sets the name and type. Omitting the slash in container: card resets the type to normal. The separate container-name property lets you assign multiple space-separated, case-sensitive names. @container card (…) only considers ancestors with that name. An unfiltered query can also pick a named container.
1cqw and 1cqh are 1% of width and height. 1cqi and 1cqb use the inline and block axes. cqmin and cqmax take the smaller and larger of cqi and cqb. Each axis finds its own eligible ancestor. The axes can use different boxes, and the @container name does not set the reference for units in its declarations.
If an axis has no eligible container, its cq* units use the small viewport, for example cqw falls back to svw. This calculation is separate from syntax support. Keep a base value outside the query and use cqi inside a size condition to require an eligible ancestor.
In an @container condition, em uses the queried container’s computed font size and rem uses the root font size. In @media, font-relative units in the condition use the browser’s initial values, which can depend on user preferences.
Relative spacing when a container exists
One ancestor, nested levels or alternatives
A condition using and/or/not selects a single ancestor eligible for all its features. width and height together can therefore skip an inline-size box and query its size ancestor. Nesting rules allows each level to select a different ancestor, always starting from the same descendant subject; it is not equivalent to merging conditions. Each comma-separated alternative selects and evaluates its own ancestor. One true alternative in every level is enough to apply the nested rule.
@container card without a condition checks for an ancestor with that name, including container-type: normal. Names are identifiers, not selectors; a box can have several. not does not turn a missing eligible ancestor into a match. The builder preserves levels and alternatives when switching between plain CSS and CSS nesting.
In Composition, choose Names and size to edit levels or alternatives. The Style, Scroll state and Anchoring scenes open a combined example with the controls for that family. The shared URL restores the selected scene and its settings.
Recipe with different ancestors
Style queries
style() reads the computed value on the container. A box with container-type: normal can answer queries about custom properties. The rule styles a descendant. The lab names both boxes card-context and combines size and style on the same ancestor when that box is eligible for both.
style(--accent) tests whether the computed value differs from the initial value according to CSS Conditional Rules. An unregistered custom property starts at the guaranteed-invalid value. With @property, it can have a valid initial value even if the box declares nothing.
style(--accent: red) compares computed values. With syntax: "<color>", red and rgb(255 0 0) represent the same color. Without registration, the query compares their tokens. var() resolves on the container. The CSS draft excludes revert and revert-layer as values inside a style condition.
Observed differences with @property. Safari 27.2 and Firefox 157 match the presence query even at the initial value. In Firefox 157, assigning initial to the example’s inheriting property computes to blue. In that case, style(--accent: blue) leaves the rule unapplied. The lab reports the control result and the observed effect separately.
and, or and not can be written inside style() or at the query level. When mixing with size, parentheses group expressions and a box needs to be eligible for all features queried by the same rule. The base card keeps a single column whenever the rule does not apply.
Ordinary properties. The draft covers forms such as style(color: red) and queries on shorthand properties. Documented browser implementations query custom properties. Those forms are reserved for future support.
Color equality with @property
Style ranges
style(--level >= 3) interprets both sides as numeric values. Use =, <, <=, > or >=. A chained range such as style(500ms <= --level < 2s) includes the lower bound and excludes the upper bound. The builder writes the expression from left to right using < or <= at each bound.
Operands can be numbers, percentages, lengths, angles, times, frequencies or resolutions. The browser converts units of the same type, such as 1000ms and 1s. A number and a percentage have different types, so 50 and 50% do not match. Unitless zero counts as a zero length when compared with a length.
The diagnostics test numeric types separately. Safari 27.2 verified ranges and all seven types in the lab. The frequency check for 1kHz and 1000Hz remained unverified in Chrome 157 and Firefox 157.
Try box B with --level: calc(1 + 2) and switch the query form. style(--level: 3) compares the computed value of an unregistered property, which retains the calculation tokens. style(--level = 3) evaluates the calculation as a number and the condition matches. The builder allows two compatible terms joined with + or − in box B. CSS also accepts var() and expressions on either side of the comparison.
Define the base style first. A browser without range support keeps the single-column card. If you need a more widely supported variant, use colon equality on an explicit state token such as --density: compact. Check the range diagnostics before interpreting a condition whose rule does not apply.
An interval with two time units
Comparing a calculation with =
Scroll state
Declare container-type: scroll-state on the element whose state you want to query. The @container rule styles its descendants.
scroll-state(scrollable: block-end) checks whether more content can be reached toward the block end. Declare the type on the region with overflow. Try none when everything fits, and physical or logical edges when you reach one end. x, y, block and inline check for room in either direction along that axis.
scroll-state(stuck: block-start) checks whether an element with position: sticky is stuck to the block-start edge. Declare it on the sticky element and style a descendant. none matches while it is free to move. You can combine two adjacent edges with and.
scroll-state(snapped: inline) checks whether the scroll region has selected that snap target on its inline axis. Declare the type on each target with scroll-snap-align and set scroll-snap-type on the region. block and inline follow the axes of the scroll region. both requires the same target to be snapped along both axes.
scrolled checks the most recent relative scroll direction in the region on each axis. Try none before the first scroll. Scroll down, pause, then scroll up. The direction persists while you pause and changes when you reverse the relative scroll, even if you return to the start. The region’s writing-mode and direction determine its logical edges and axes.
Change the border when scrolling toward the block end
Combine scrolled and scrollable with and or or inside scroll-state(). Use not to negate a condition. You can add an inline-size threshold or a style() query to the same rule. All conditions are evaluated on the same ancestor. Combine scroll-state with inline-size or size to query its size as well. The lab checks the preview’s content box and the recipe starts with a 12 rem region.
Combine recent direction, available scroll and size
The browser takes a snapshot of the state after layout. Keep the size and flow of responding descendants stable. Changing the border thickness or the visibility of a control can change the scroll range and trigger another evaluation. The recipe changes the border style and keeps its thickness.
Choose an animation with scroll() or view() when you need continuous progress. Use the overflow-block or overflow-inline media queries to find how the medium handles viewport overflow along each axis.
Keep scrolling, snapping and sticky positioning as the base behavior. Keep content and controls accessible when the conditional rule does not apply. Chrome 133 introduced scrollable, stuck and snapped. Chrome 144 introduced scrolled. The lab checks the active query separately.
Anchor position queries
Declare container-type: anchored on the positioned panel and apply @container anchored(fallback: …) to its content. The circle marks the anchor and the panel stays visible so you can compare its positions.
By default, the browser tries the position-try-fallbacks alternatives in list order when the position overflows. fallback: none matches while the initial position is in use. The last fallback can stay active as long as it fits. In the lab, move the anchor to the block end so flip-block runs out of room and the panel returns above it.
Compare the initial position with flip-block
Anchor near the bottom edge
Anchor near the top edge
Physical areas such as right stay on the same side. Logical areas such as inline-end follow the writing mode and direction. In horizontal writing, a right fallback matches inline-end in LTR and inline-start in RTL. any accepts any area on its axis. Use bottom any in the query to match an area such as bottom right.
flip-block and flip-inline follow the logical axes. flip-x and flip-y act on the physical axes. flip-start swaps the starts of the two axes and their ends. Write the tactics in the order they appear in the active fallback. Query flip-start flip-block and flip-block flip-start separately.
Query a named position rule with a tactic
The panel tries --below and then its inline reflection. To detect the second alternative, the condition includes the name and flip-inline.
Combine values with and or or inside anchored(), or negate one with not. To add an inline-size threshold on the same panel, declare it as inline-size anchored. You can also combine the condition with style(--density: compact) on that panel.
Keep the panel in flow as the base layout and enable positioning with @supports. If the browser supports anchor positioning but lacks anchor position queries, the panel moves and keeps its dashed border. The diagnostic checks both capabilities separately.
CSSOM describes syntax, not matching
CSSContainerRule exposes conditionText and the singular containerName/containerQuery fields. The optional conditions API returns name/query pairs for alternatives; singular fields may be empty strings for a list. The diagnostic detects that API and preserves its original data. A retained rule, a name/query pair or missing conditions does not demonstrate application, selection or comma support. The scene uses CSS witnesses and independent checks without relying on Element.matchContainer().
Common mistakes
Identify the element, axis and computed property before changing the threshold.
Querying the card itself
- Expected result
- The card switches columns when it reaches the threshold.
- Cause
- The type was set on the card and the rule also tries to style it. The search begins with its ancestors.
- Solution
- Set the type on a wrapper and apply the rule to the card inside it.
Asking for an axis the box cannot expose
- Expected result
- The block-size or orientation condition uses the nearest box.
- Cause
- inline-size only enables the inline axis. CSS can skip that box to find an ancestor with both axes.
- Solution
- Query inline-size if that axis is enough. To query both, use size and give the container space.
Measuring from the outer edge
- Expected result
- The rule matches when the visible box is 320 px wide.
- Cause
- Padding and borders can take up part of the declared width and leave a smaller content box.
- Solution
- Inspect the content box in DevTools or in the lab preview.
The condition matches and the style stays put
- Expected result
- The card shows the rule’s two columns.
- Cause
- Another applicable declaration wins the cascade, or the selector targets a different element.
- Solution
- Inspect the selector and the winning declaration in the descendant’s computed styles.
The sticky heading never responds
- Expected result
- The heading content changes when the heading sticks.
- Cause
- The region containing the heading was given the scroll-state type.
- Solution
- Declare the type on the heading itself and apply the rule to one of its descendants.
The panel changes sides and keeps its dashed border
- Expected result
- The border changes when the query matches the active fallback.
- Cause
- The query may target another element, omit a fallback tactic or require a feature the browser lacks.
- Solution
- Query the anchored panel, target its content and check the name and tactic order. Review the positioning and query diagnostics separately.
Support and compatibility
The lab distinguishes support, matching and application. It tests support with control conditions, observes matches through CSS and reads the card’s computed grid and border. A threshold that is not reached leaves the base style visible.
Keep a one-column base layout that works on its own. Size queries and name-only queries have their own Baseline statuses. Check comma-separated lists and CSSContainerRule.conditions separately.
Queries for ordinary CSS properties, such as style(color: red), are still pending. CSS Conditional Rules Level 5 also proposes Element.matchContainer() and ContainerQueryList. The lab observes CSS witnesses and uses CSSContainerRule only to describe the rule. Size operands using var(), env(), sibling-index(), and sibling-count() are pending verification in a stable browser.