:scope CSS Pseudo Class
Description
The CSS :scope
pseudo-class represents elements that are a reference point, or scope, for selectors to match against. It can be used to scope CSS styles to a specific subtree of the document, preventing them from affecting other elements on the page.
The :scope
pseudo-class is particularly useful for CSS modularity and component-based development. It allows you to isolate the CSS styles for a particular component, ensuring that they do not conflict with the styles of other components on the page.
To use the :scope
pseudo-class, simply prefix it to any CSS selector. For example, the following rule will style all <h1>
elements that are descendants of a div
element with the class my-component
:
.my-component :scope h1 {
color: red;
}
The
:scope
pseudo-class is currently supported by all major browsers, except for Internet Explorer.Here is an example of how to use the
:scope
pseudo-class to scope CSS styles to a component:<div class="my-component">
<h1>This is a heading</h1>
<p>This is a paragraph</p>
</div>
.my-component :scope h1 {
color: red;
}
.my-component :scope p {
color: blue;
}
In this example, the
<h1>
element inside the .my-component
element will be red, and the <p>
element will be blue. The CSS styles for the .my-component
component will not affect any other elements on the page.The
:scope
pseudo-class is a powerful tool for CSS modularity and component-based development. It allows you to isolate the CSS styles for a particular component, ensuring that they do not conflict with the styles of other components on the page.
Syntax
:scope { /* ... */ }
Example
<p id="para">
This is a paragraph. It is not an interesting paragraph. Sorry about that.
</p>
<p id="output"></p>
<script>
const paragraph = document.getElementById("para");
const output = document.getElementById("output");
if (paragraph.matches(":scope")) {
output.textContent = "The first paragraph is its own scope, as expected!";
}
</script>
Browser Support
The following table will show you the current browser support for the CSS :scope
pseudo class.
Desktop | |||||
79 | 27 | 32 | 15 | 7 |
Tablets / Mobile | |||||
27 | 32 | 15 | 7 | 1.5 | 4.4 |
Last updated by CSSPortal on: 1st October 2023