CSS @scope Rule
Example
Here we use two separate @scope blocks to match <a> elements within the .ex1 class and the .ex2 class. :scope is used to select and style the scope roots themselves. In this example, the scope roots are the <div> elements that have the classes applied to them:
@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 »
More "Try it Yourself" examples below.
Definition and Usage
The CSS @scope
rule allows you to select
elements in specific DOM subtrees.
With this at-rule you can target elements precisely without writing overly-specific selectors.
This at-rule also reduces coupling between your selectors and the DOM structure.
Look at the following HTML:
<div class="container">
<div class="news">
<h2>Some header</h2>
<img
src="example.jpg" alt="Some image">
</div>
</div>
Here we have some nested <div> elements, and if we want to style the <h2> and <img> elements within the container/news section above you must write (without using @scope):
Example
.container .news h2 {
color: green;
}
.container .news img {
border: 2px solid maroon;
}
Try it Yourself »
With the @scope rule you can target elements precisely without writing overly-specific selectors, like this:
Example
Here, we target only the <h2> and <img> elements in the .container component, you set .container as the scoping root of the @scope at-rule:
@scope (.container) {
h2 {
font-size: 30px;
color: green;
}
img {
border: 5px
solid maroon;
}
}
Try it Yourself »
The @scope
rule contains one or more rulesets,
and can be
used in two ways:
- As a standalone block inside your CSS, in which case it includes a prelude section that includes scope root and optional scope limit selectors - these define the upper and lower bounds of the scope.
- As inline styles included inside a <style> element in your HTML, in which case the prelude is omitted, and the enclosed ruleset is automatically scoped to the <style> element's enclosing parent element.
Browser Support
The numbers in the table specify the first browser version that fully supports the at-rule.
At-rule | |||||
---|---|---|---|---|---|
@scope | 118 | 118 | No | 17.4 | 104 |
CSS Syntax
@scope (scope root) {
rulesets
}
or
/* donut scope */
@scope (scope root) to (scope limit) {
rulesets
}
More Examples
Example
A donut scope only targets elements that are placed 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 »