webdevpuneet.com

CSS @scope Tutorial: Scoped Component Styles Without BEM

CSS @scope Tutorial: Scoped Component Styles Without BEM · Cards · Plain HTML, CSS & JS · Live preview

CategoryCards

About this UI Snippet

CSS @scope: Style Inside a Component Without Naming Everything

Screenshot of the CSS @scope Tutorial: Scoped Component Styles Without BEM snippet rendered live

Large stylesheets leak: a rule for .card h2 meant for one place restyles a nested card somewhere else, so teams invent BEM names, CSS modules or Shadow DOM. The @scope at-rule gives the cascade a boundary. @scope (.theme-sunrise) { .card { ... } } styles .card only inside .theme-sunrise. This snippet shows two scopes and the "donut" that keeps nested components safe.

A scope root

@scope (.theme-sunrise) makes .theme-sunrise the root. Selectors inside are relative to it, so plain .card, h2 and button need no prefix. :scope refers to the root itself, used here to define the theme's custom properties.

Donut scoping with a lower bound

@scope (.theme-sunrise) to (.card-body) ends the scope where .card-body begins. Everything inside that element is outside the scope, so the nested card keeps its neutral dashed look. This is how a tabs component styles its own panels without reaching into whatever the author put inside them.

Same markup, two scopes

The Sunrise and Tide sections contain identical HTML. One scope gives rounded, filled cards and the other square, outlined ones. You re-theme by changing the wrapper class, not the markup.

Proximity wins

When two scopes could both match, the one whose root is closer to the element wins, which is why nested themes work without !important. Specificity is unchanged by @scope, so inner selectors stay low.

Support

@scope works in Chrome, Edge, Safari and Firefox 146 and later. In older browsers the rules are ignored, so ship fallback classes where you need them. For container-driven layout see the container query card.

Practical advice

Scope at the component boundary, not at the page. A scope root like a section or custom wrapper is cheap to match, and the lower bound is the single most useful part: put it on the slot where authors drop their own content. Avoid scoping to the whole body, because then nothing is isolated, and test with the nested component in place before shipping.

What's included

Features

Plain selectors
No BEM prefixes: .card and h2 are enough inside a scope.
Donut scoping
to (.card-body) stops the scope at the content slot.
:scope root
The scope root defines the theme variables.
Two themes, one markup
Sunrise and Tide share every element and differ only by wrapper.
Nested card protection
The inner card keeps its own style because it is outside the scope.
Proximity resolves conflicts
The nearer scope root wins when scopes overlap.
No JavaScript
The behaviour is pure CSS; the script only reports support.
Visible focus
Both button styles keep a clear focus outline.

Step by step

How to Use

  1. 1
    Pick the rootChoose the element that owns the component, here .theme-sunrise and .theme-tide, and write @scope (.theme-sunrise) { ... }.
  2. 2
    Write short selectors insideInside the block use .card, h2 and button without a prefix; they only match descendants of the root.
  3. 3
    Use :scope for the rootDefine custom properties on :scope so every rule inside can read --accent and --soft.
  4. 4
    Add a lower boundWrite to (.card-body) after the root to stop the scope at that element, protecting nested components.
  5. 5
    Re-theme by changing the wrapperSwap theme-sunrise for theme-tide on the section; the markup stays identical.
  6. 6
    Check supportThe note under the demo reports whether CSSScopeRule exists in your browser.

Real-world uses

Common Use Cases

Design-system themes
Offer light, dark and brand variants of a component by changing a wrapper class, without duplicating selectors or generating prefixed class names.
Component libraries and CMS blocks
Keep a block's styles from leaking into editor-supplied content that lives inside it, using a lower bound.
Third-party widgets
Embed a widget on pages with unknown CSS and confine its rules to its own root.
Replacing BEM and CSS-in-JS
Cut long class names and build tooling by using the platform feature that solves the same leakage.

Got questions?

Frequently Asked Questions

No. @scope limits where rules apply but does not stop outside rules from reaching in or hide the markup. Shadow DOM provides true encapsulation in both directions. @scope is lighter and fits ordinary server-rendered HTML.

It sets a lower boundary. Elements inside .card-body are outside the scope even though they are descendants of the root, so nested components are not touched. It is called donut scoping because the scope has a hole.

No. Selectors inside keep their normal specificity, and :scope adds the specificity of a pseudo-class. What it adds is the scoping-proximity step, where the closer scope root wins before source order is considered.

Chrome and Edge 118 and later, Safari 17.4 and later, and Firefox from 146. In older versions the whole block is ignored, so plan a fallback if you must support them.

Copy & paste

Source Code

<main class="sc-page">
  <h1>Scoped styles, no class prefixes</h1>
  <p class="sc-sub">The same card markup in two themes, and a nested card that the outer scope cannot reach. All of it from <code>@scope</code>.</p>

  <div class="sc-grid">
    <section class="theme-sunrise" aria-label="Sunrise theme">
      <div class="card">
        <h2>Sunrise plan</h2>
        <p class="price">&pound;12<span>/mo</span></p>
        <div class="card-body">
          <p>Applies .card styles inside .theme-sunrise only.</p>
          <div class="card"><h2>Nested card</h2><p>This one sits in the donut hole, so the outer scope stops here.</p></div>
        </div>
        <button type="button">Choose Sunrise</button>
      </div>
    </section>

    <section class="theme-tide" aria-label="Tide theme">
      <div class="card">
        <h2>Tide plan</h2>
        <p class="price">&pound;18<span>/mo</span></p>
        <div class="card-body">
          <p>The same markup, a different scope, different styles.</p>
          <div class="card"><h2>Nested card</h2><p>Untouched by the Tide scope too.</p></div>
        </div>
        <button type="button">Choose Tide</button>
      </div>
    </section>
  </div>
  <p class="sc-note" id="scNote"></p>
</main>

Extend with AI

Take This Snippet Further With AI

Paste this snippet into an AI coding assistant and ask it to explain the root, :scope and the "to" lower bound, and how proximity decides which scope wins. Useful follow-ups: add a third dark theme, scope a tabs component whose panels hold arbitrary content, or convert a BEM stylesheet into scoped rules. Ask it to keep the donut hole for nested cards.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build a demo of the CSS @scope rule in plain HTML and CSS.

Requirements:
- Two sections with the same card markup (heading, price, a .card-body containing text and a nested card, and a button): one with class theme-sunrise and one with theme-tide.
- @scope (.theme-sunrise) to (.card-body) and @scope (.theme-tide) to (.card-body), each defining theme custom properties on :scope and styling plain .card, h2, .price and button selectors (Sunrise: rounded, filled; Tide: square, left border, outlined button with hover).
- Outside the scopes, give the nested .card-body .card its own neutral dashed style to prove the donut hole works.
- Visible focus styles on both buttons, a responsive two-column grid, and a note set by a script that checks typeof CSSScopeRule.
- No class prefixes or BEM names anywhere.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.