:scope CSS Pseudo Class

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

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
Edge Chrome Firefox Opera Safari
792732157
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
27321571.54.4

Last updated by CSSPortal on: 1st October 2023