CKTIS / CSS
@container — querying an ancestor container
The @container rule conditions descendant styles on a selected ancestor container’s size or style, so a component can respond to its placement rather than only the viewport.
Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required
Syntax
@container <container-condition># {
<block-contents>
}@container [<container-name>]? <container-condition> { <stylesheet> } is a conditional group rule. For each styled element, the browser selects the nearest ancestor query container eligible for every feature in the condition; an optional name filters the candidates. Size queries require container-type: inline-size or size, while style queries examine computed styles exposed by a container.
A component can therefore change layout when its own panel has enough room even if the viewport is unchanged. The condition styles descendants of the container: an element cannot query its own size to style itself. If no eligible ancestor exists, the query is unknown and the block does not apply. A container name can deliberately select a qualifying context beyond a nearer unrelated container.
Combine and, or, and not only as the grammar permits, and note that em units in a condition use the query container’s computed font size. Nested queries can select different containers and cannot always be flattened. The example establishes an inline-size container, observes its child at 300 px, narrows it to 100 px, and reads the actual computed --state value.
Examples
const style = document.createElement('style');
style.textContent = `.host { container-type: inline-size; width: 300px; }
.target { --state: base; }
@container (inline-size > 200px) { .target { --state: wide; } }`;
document.head.append(style);
const host = document.createElement('div');
host.className = 'host';
host.innerHTML = '<div class="target">card</div>';
document.body.append(host);
const target = host.firstElementChild;
const wide = getComputedStyle(target).getPropertyValue('--state').trim();
host.style.width = '100px';
await new Promise(requestAnimationFrame);
const narrow = getComputedStyle(target).getPropertyValue('--state').trim();
console.log('300px=' + wide + '; 100px=' + narrow);Result
300px=wide; 100px=base
The @container rule conditions descendant styles on a selected ancestor container’s size or style, so a component can respond to its placement rather than only the viewport.