W3docs

CSS :scope Pseudo Class

The :scope CSS pseudo-class represents scope elements. Read about the pseudo-class and practice with examples.

The CSS :scope pseudo-class represents the reference element for selectors, such as the root element in a Shadow DOM or the element passed to querySelector().

It is commonly used in JavaScript DOM queries to limit selector matching to a specific subtree. Note that the deprecated <style scoped> attribute is no longer supported in modern browsers, but :scope remains relevant for DOM querying.

Version

Selectors Level 4

Syntax

CSS :scope syntax

:scope {
  css declarations;
}

Example of the :scope selector:

CSS :scope code example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .container {
        margin: 40px auto;
        max-width: 700px;
        background-color: #eeeeee;
        padding: 20px;
        box-shadow: 0 0 4px rgba(0, 0, 0, 0.25);
      }
      section {
        padding: 30px;
      }
    </style>
  </head>
  <body>
    <h2>:scope selector example</h2>
    <div class="container">
      <section>
        <p>
          Inside the scope.
        </p>
      </section>
    </div>
    <script>
      const container = document.querySelector('.container');
      const scopeElement = container.querySelector(':scope > section');
      scopeElement.style.backgroundColor = '#1c87c9';
      scopeElement.style.color = '#fff';
    </script>
  </body>
</html>

Practice

Practice

What does the scope in CSS refer to?