Skip to main content

Harshal V. LADHE

CSS @scope: Component-Level Style Isolation

Limit where selectors match, with donut scopes and proximity.
Published at:
Last updated:
Estimated reading time:8 min read
CSS @scope tutorial cover: component-level style isolation with a donut scope that excludes a content slot, and scope proximity where the nearest root wins in nested themes(opens full-size image in a new tab)
A donut scope that stops at the content slot, and nested themes where the nearest root wins.

Introduction

CSS selectors match anywhere in the document. A rule like .card img styles every image inside every card, including images in a nested card and in user content dropped into a card's body. Teams have worked around this with BEM naming, build tools that rewrite class names, or Shadow DOM.

@scope handles it in plain CSS. It lets you say "these rules apply inside .card", and optionally "but stop at .content". It also adds scope proximity to the cascade, so when two scoped rules compete, the one whose root is closer to the element can win.

Basic Usage

@scope (.card) {
  :scope {
    padding: 1rem;
    border: 1px solid #d4d4d8;
  }

  img {
    border-radius: 50%;
  }

  > header { /* Only a header that is a direct child of the card */ }
}

The selector in parentheses, the rule's prelude, picks the scoping root. Every element that matches .card starts its own scope, and the rules inside the block only match elements inside one of those scopes.

  • :scope matches the root itself, so the first rule styles the card element.
  • Plain selectors are relative to the root. img behaves like :scope img, an image anywhere inside the card.
  • A leading combinator changes that relationship: > header is a direct child of the card. The element a selector targets must still be inside the scope, so + .card (a sibling) never matches.

Because of the implied :scope, .dark-mode img inside the block needs a .dark-mode element inside the card. To check an ancestor outside the root, place :scope yourself: .dark-mode :scope img.

Scope Limits: Donut Scope

A card often has a slot for content it doesn't own: a user's bio, a CMS-rendered body, or another component. Add a scoping limit with to so the card's rules don't reach into it:

@scope (.card) to (.content) {
  p {
    font-weight: 600;
    text-transform: uppercase;
  }

  a {
    padding: 0.375rem 0.875rem;
    border-radius: 999px;
    background: indigo;
    color: white;
  }
}
<article class="card">
  <p>Profile</p>                <!-- in scope: uppercase -->
  <a href="/follow">Follow</a>  <!-- in scope: pill button -->

  <div class="content">         <!-- the limit: out of scope -->
    <p>User bio with <a href="/x">a link</a>.</p>  <!-- out of scope: untouched -->
  </div>
</article>

The scope runs from the root down to any .content inside it and stops there: styled on the outside with a hole in the middle, hence donut scope.

  • The limit element itself is excluded. To keep .content in scope and exclude only what's inside it, write to (.content > *).
  • A limit can use :scope. to (:scope > .content) stops only at a .content that is a direct child of the card.

Both the root and the limit accept selector lists, so @scope (.card, .panel) to (.content, .embed) is valid.

The Root Adds No Specificity

This is the biggest difference from nesting. A nested rule includes its parent's specificity; a scoped rule doesn't include the root's:

/* Nesting: means "#hero img", specificity (1,0,1) */
#hero {
  img { border-radius: 50%; }
}

/* @scope: specificity (0,0,1), the same as a bare img selector */
@scope (#hero) {
  img { border-radius: 50%; }
}

The root decides where a rule can match, not how strongly. Only an explicit :scope in the inner selector counts: :scope img is (0,1,1). The nesting selector & also matches the root, but with zero specificity, like :where(:scope). For a refresher on how specificity is written, see The Specificity Arms Race.

Scope Proximity in the Cascade

When two declarations compete, the browser checks origin and importance, then context, the style attribute, cascade layers and specificity. Scope proximity comes next, followed only by order of appearance.

So proximity only decides between declarations tied on everything above it, including specificity. When it applies, the declaration whose scoping root is the fewest steps up the tree wins. An unscoped rule counts as infinitely far away.

The Nested-Theme Problem

Themes nest: a dark panel inside a light page, with a light card inside that panel.

.theme-light a { color: #1d4ed8; }
.theme-dark a  { color: #93c5fd; }
<div class="theme-light">
  <div class="theme-dark">
    <div class="theme-light">
      <a href="#">Which colour am I?</a>
    </div>
  </div>
</div>

Both rules match with the same specificity, so the later one wins and the link gets the pale dark-theme colour on a light background. Reordering the rules just moves the bug to the opposite nesting. With @scope, the nearest theme wins:

@scope (.theme-light) {
  a { color: #1d4ed8; }
}

@scope (.theme-dark) {
  a { color: #93c5fd; }
}

The innermost .theme-light is one step above the link and .theme-dark is two, so the light rule wins, even though the dark block comes later. Proximity only works while the competing rules have equal specificity: a scoped a.link in the farther theme would still win. Use the same selectors in every theme.

Try It Live

The top demo nests three theme cards: light, dark, then light again. Switch between descendant selectors, @scope and @scope with a more specific dark rule, and the readout reports whether the innermost card keeps its light colours. In the bottom demo, tick the checkbox to add to (.content) and watch the card's styles stop leaking into the user-written bio.

CSS @scope Playground

Three theme cards nested light, dark, light: switch between descendant selectors, @scope, and @scope with a more specific dark rule to see scope proximity fix the innermost card and specificity override it again, then toggle a to (.content) limit to stop a profile card's styles leaking into its user bio.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>CSS @scope Playground</title>
  </head>
  <body>
    <main class="playground">
      <header class="playground-header">
        <h1>Theme Cards and Donut Scope with @scope</h1>
        <p>Three theme cards nested inside each other: light, dark, then light again. Switch how the theme rules are written and watch which colours the innermost card picks up.</p>
      </header>

      <p class="tip" id="scope-support" hidden>Your browser doesn't support <code>@scope</code> yet (Chrome and Edge 118, Firefox 146, Safari 26.4), so the two <code>@scope</code> options are disabled.</p>

      <fieldset class="control-group">
        <legend>Theme rules</legend>
        <div class="segmented-control" role="radiogroup" aria-label="How the theme rules are written">
          <label class="segment"><input type="radio" name="mode" value="descendant" checked><span>Descendant selectors</span></label>
          <label class="segment"><input type="radio" name="mode" value="scope"><span>@scope</span></label>
          <label class="segment"><input type="radio" name="mode" value="specific"><span>@scope, dark more specific</span></label>
        </div>
      </fieldset>

      <section class="demo-area" id="themes" data-mode="descendant" aria-label="Nested theme cards">
        <div class="card theme-light">
          <h2 class="title">Light card</h2>
          <p class="text">Outer card. <a class="link" href="#">A link</a></p>
          <div class="card theme-dark">
            <h2 class="title">Dark card</h2>
            <p class="text">Nested inside the light card. <a class="link" href="#">A link</a></p>
            <div class="card theme-light" id="innermost">
              <h2 class="title">Light card again</h2>
              <p class="text" id="innermost-text">Nested inside the dark card. <a class="link" href="#">A link</a></p>
            </div>
          </div>
        </div>
      </section>

      <output class="readout" id="themes-readout" aria-live="polite"></output>

      <fieldset class="control-group">
        <legend>Scope limit</legend>
        <label class="checkbox-field">
          <input type="checkbox" id="limit">
          <span>Stop the profile card's styles at <code>.content</code></span>
        </label>
      </fieldset>

      <section class="demo-area" id="donut" aria-label="Profile card with user content">
        <article class="profile">
          <p class="kicker">Profile</p>
          <h2 class="name">Ada Byron</h2>
          <a href="#">Follow</a>
          <div class="content">
            <p>User-written bio. I write about <a href="#">analytical engines</a> and poetry.</p>
          </div>
        </article>
      </section>

      <output class="readout" id="donut-readout" aria-live="polite"></output>
    </main>

    <script src="./index.js"></script>
  </body>
</html>

Read-only
Ln –, Col –HTML2.9 KBUTF-8

Starting sandbox…

No console output yet.

Implicit Scope with an Inline <style>

Leave out the prelude and @scope uses the parent element of the <style> element as its root:

<section class="promo">
  <style>
    @scope {
      :scope { padding: 2rem; background: #fef3c7; }
      h2 { font-size: 2rem; }
    }
  </style>

  <h2>Spring sale</h2>
</section>

<h2>This heading is outside the section and keeps its normal size</h2>

This suits server-rendered fragments that ship their own styles: the CSS travels with the markup, can't affect the rest of the page, and needs no unique class name. @scope to (.content) { ... } adds a limit without a root selector.

Using @scope Inside @layer

The usual pattern is to put component scopes inside a components layer:

@layer reset, base, components, utilities;

@layer components {
  @scope (.card) to (.content) {
    img { border-radius: 50%; }
  }
}

@layer utilities {
  .rounded-none { border-radius: 0; }
}

Layers are checked before proximity, so .rounded-none in the later utilities layer beats the scoped img rule, however close its root is. Proximity only decides between scoped rules within the same layer.

How It Compares

ApproachStops styles leaking outStops styles leaking inNeeds a build step or JavaScript
BEM namingBy conventionBy conventionNo
CSS ModulesYes, unique class namesNoYes, a bundler
Shadow DOMYesYes, except inherited and custom propertiesNo with <template shadowrootmode>, otherwise JavaScript
Cascade layersNo, they order rules but don't limit where they matchNoNo
@scopeYes, inside the root and above the limitNoNo

@scope lets inner elements use short names like .title without BEM prefixes or a bundler, and adds donut limits and proximity that neither offers. Shadow DOM is stronger, since outer selectors can't reach in, but each component needs its own shadow root and global styles must be added again inside it.

Browser Support and Fallbacks

@scope is supported in Chrome and Edge 118, Firefox 146 and Safari 26.4. Safari first shipped it in 17.4, but 26.0 to 26.3 didn't apply scoped rules to <input> and <textarea>, so treat 26.4 as complete.

A browser without @scope drops the whole block. Keep the styles a component can't do without in ordinary rules and use @scope for refinements, or check typeof CSSScopeRule !== "undefined" in JavaScript to load a fallback. Avoid @supports at-rule(@scope): at-rule() is newer than @scope itself, so it returns false in many browsers that support it.

Common Pitfalls

1. Forgetting That Inheritance Ignores the Limit

A donut limit stops selectors from matching, not inheritance. If :scope sets color or font-family on the card, elements inside .content still inherit them. Set inherited properties on in-scope elements, or reset them on the limit element with an unscoped rule.

2. Excluding the Limit Element by Accident

@scope (.card) to (.content) { .content { ... } } never matches, because the limit is outside the scope. Use to (.content > *) if the limit element should still be styled.

3. Adding :scope Everywhere

:scope img is (0,1,1), while img alone is (0,0,1) and means the same thing. The extra specificity can break the equal-specificity setup proximity relies on. Use :scope only to target the root or anchor a combinator.

4. Moving an Inline <style> Element

With a prelude-less @scope, the root is the <style> element's parent. If a framework hoists it into <head>, the root becomes <head> and the rules match nothing on the page.

Where Should You Use This?

  • Component styles with short class names (.title, .meta, .actions) that don't collide with other components
  • Cards, tabs and layouts with a slot for content you don't control
  • Nested themes, colour schemes or density modes, where the closest setting should win
  • Server-rendered fragments that carry their own <style> element

Reach for something else when outside styles must not get in (Shadow DOM), when the problem is priority between whole groups of rules (@layer), or when a variant should follow a value set on a parent (container style queries).

Frequently Asked Questions

Key Takeaway

@scope limits where selectors match: from a root, optionally down to a limit, with no extra specificity from the root. When scoped rules tie on layers and specificity, the nearest root wins, which fixes nested themes without specificity tricks. Together with @layer, it covers most of what naming conventions and CSS Modules used to do, in plain CSS.

Changelog

  • — Initial publication.
This tutorial is licensed under CC BY 4.0 by the author.

Share this tutorial

Spotted a mistake or something outdated in this tutorial? Suggest a correction.

  • One-Line Theme-Aware Colors with light-dark()

    A single declaration per color, resolved automatically for both light and dark mode.
    The light-dark() CSS function collapses a light value and a dark value into one declaration, resolved by color-scheme — no duplicate custom properties, no @media (prefers-color-scheme) block per themed property.
    Published at:
  • Theming Native Controls with accent-color

    Theme native checkboxes, radios and sliders with one property.
    The accent-color property themes the checked and filled parts of native checkboxes, radio buttons, switches, range sliders and progress bars — including their indeterminate states — while keeping real browser controls with full native behaviour and accessibility, plus how it pairs with color-scheme and what it leaves alone.
    Published at:
  • CSS Custom Highlight API: ::highlight() for Search Results

    Highlight search matches with CSS without touching the DOM.
    Highlight search results with the CSS Custom Highlight API: ::highlight(), CSS.highlights, StaticRange, priority, accessibility and a mark fallback.
    Published at: