CSS @scope rule

Definition and Usage

CSS @scope The rule allows you to select elements within a specific DOM subtree.

With this @ rule, you can accurately locate elements without writing overly specific selectors.

This @ rule also reduces the coupling between the selector and the DOM structure.

Instance

Example 1

Here, we use two independent @scope Block to match <a> elements in .ex1 and .ex2 classes. :scope is used to select and set the style of the scope itself. In this example, the scope root is the <div> element that applies the class:

@scope (.ex1) {
  :scope {
    background-color: salmon;
    padding: 10px;
  }
  a {
    color: maroon;}
  }
  a:hover {
    color: blue;
  }
}
@scope (.ex2) {
  :scope {
    background-color: beige;
    padding: 10px;
  }
  a {
    color: green;
  }
}

Try it yourself

See the following HTML:

<div class="container">
  <div class="news">
    <h2>Some header</h2>
    <img src="example.jpg" alt="Some image">
  </div>
</div>

There are some nested <div> elements. If we want to set styles for the <h2> and <img> elements in the above container/news section, we must write the following content (without using @scope):

Example 2

.container .news h2 {
  color: green;
}
.container .news img {
  border: 2px solid maroon;
}

Try it yourself

Using @scope Rules, you can precisely locate elements without writing overly complex selectors, as shown below:

Example 3

Here, we set .container as the root scope of the @scope rule for <h2> and <img> elements within the .container component:

@scope (.container) {
  h2 {
    font-size: 30px;
    color: green;
  }
  img {
    border: 5px solid maroon;
  }
}

Try it yourself

@scope Rules contain one or more rule sets and can be used in two ways:

  • As an independent block in CSS, in this case, it contains a leading part, including the scope root and an optional scope limitation selector - these define the upper and lower boundaries of the scope.
  • As an inline style within the <style> element in HTML, in this case, the leading part is omitted, and the contained rule set will automatically apply to the parent element of the <style> element.

Example 4

"Donut scope" is only for elements located between two elements in the ancestor tree. Here is an example:

@scope (.container) to (.news) {
  h2 {
    font-size: 30px;
    color: green;
  }
  img {
    border: 5px solid maroon;
  }
}

Try it yourself

CSS syntax

@scope (Scope root) {
  Rule set
}

or

/* Donut scope */
@scope (Scope root) to (Scope limitation) {
  Rule set
}

Browser support

The numbers in the table represent the first browser version that fully supports the @ rule.

Chrome Edge Firefox Safari Opera
118 118 Not Supported 17.4 104