Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

@scope — selector scope with a lower boundary

The @scope rule restricts nested style-rule matching to a subtree or fragment defined by roots and optional lower limits.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

@scope <scope-boundaries>? {
  <block-contents>
}
<scope-boundaries> = [ [ ( <scope-start> ) ]? [ to ( <scope-end> ) ]? ]!

@scope <scope-boundaries>? { <block-contents> } creates a separate scope for every element matched by the start selector. A root is included, while an element matched by the end selector and its entire subtree are excluded. If the start selector is omitted, the root is normally the parent of the stylesheet’s owner node. Pseudo-elements cannot be roots or limits, and invalid entries make the unforgiving prelude selector lists fail.

Inner selectors match only subjects that remain in scope and are relative to the root by default. :scope matches the root; & behaves as :where(:scope), so it adds no specificity. A prelude selector does not add its specificity to an inner rule. In the cascade, selector specificity is compared first, scope-root proximity next, and source order after that.

A component, theme region, or document fragment can therefore be isolated without adding a class to every descendant. The example starts a scope at .card and stops before .nested. Its direct paragraph becomes green, but the paragraph beyond the limit and the outside element remain black. The to (.nested) prelude and the CSSScopeRule properties confirm both boundaries.

Examples

const style = document.createElement('style');
style.textContent = `p { color: rgb(0 0 0); }
@scope (.card) to (.nested) { p { color: rgb(0 128 0); } }`;
document.head.append(style);
const card = document.createElement('section');
card.className = 'card';
card.innerHTML = '<p class="direct">direct</p><div class="nested"><p class="limited">limited</p></div>';
const outside = document.createElement('p');
outside.textContent = 'outside';
document.body.append(card, outside);
const rule = style.sheet.cssRules[1];
console.log('rule=' + rule.constructor.name + '; start=' + rule.start + '; end=' + rule.end + '; direct=' + getComputedStyle(card.querySelector('.direct')).color + '; limited=' + getComputedStyle(card.querySelector('.limited')).color + '; outside=' + getComputedStyle(outside).color);

Result

rule=CSSScopeRule; start=.card; end=.nested; direct=rgb(0, 128, 0); limited=rgb(0, 0, 0); outside=rgb(0, 0, 0)

The @scope rule restricts nested style-rule matching to a subtree or fragment defined by roots and optional lower limits.

Sources