2 min read

CSS Scoped Styles (@scope)

The @scope at-rule allows you to select elements within a specific DOM subtree, targeting that subtree precisely without writing overly specific selectors or relying on naming conventions like BEM. It essentially creates a "donut scope" where you can style a container but exclude certain inner parts.

1. The Concept

Traditionally, CSS is global. To style a specific component, you often use long class names (.card__title) or nested selectors (.card .title). @scope formalizes this by defining a root element for the scope and optionally a lower boundary.

2. Basic Scoping

You define a scope root (the start of the scope). Styles inside the block only apply to descendants of that root.

@scope (.card) {
  /* Matches .card img */
  img {
    border-radius: 5px;
  }

  /* Matches .card .title */
  .title {
    font-size: 1.5rem;
  }
}

This is similar to nesting (.card { img { ... } }), but with different specificity implications. The specificity of the scope root (.card) is not added to the selectors inside.

3. Donut Scoping (Lower Boundary)

The real power of @scope is defining a lower boundary. This allows you to style a component but stop styling when you hit a nested component (the "hole" in the donut).

Syntax: @scope (scope-start) to (scope-end)

/* Style everything inside .card, BUT stop at .content */
@scope (.card) to (.content) {
  p {
    color: gray;
  }
}

In this example:

  • <div class="card"><p>Hello</p></div>: The paragraph is styled (gray).
  • <div class="card"><div class="content"><p>Hello</p></div></div>: The paragraph is not styled because it is inside the lower boundary (.content).

4. The :scope Pseudo-class

Inside the @scope block, :scope refers to the scope root element itself.

@scope (.card) {
  :scope {
    background: white;
    border: 1px solid black;
  }
}

5. Specificity

Selectors inside @scope do not inherit the specificity of the scope root. However, @scope adds a small amount of specificity to the rules inside it, making them win over un-scoped rules of the same specificity, but losing to higher specificity global rules.

programming/css/css programming/css/selectors programming/css/specificity programming/css/css-nesting