Get started with 33% off your first certification using code: 33OFFNEW

An introduction to `@scope` in CSS

2 min read
Published on 26th June 2023
An introduction to `@scope` in CSS

In the world of CSS, there's a sea of rules, declarations, and selectors that provide powerful control over the visual presentation of web content. One lesser-known, yet valuable tool in the CSS toolbox is the @scope rule. It's a CSS construct that allows for better encapsulation of style declarations, improving the organization and maintainability of your stylesheets.

What is the @scope Rule?

The @scope rule is part of the CSS Scoping Module Level 1, a working draft specification designed to bring modular programming principles to CSS. By creating a new scope for style declarations, @scope helps isolate a block of CSS, which ensures that the contained styles apply only to a specified portion of the DOM.

Syntax and Usage

The syntax for @scope involves defining a selector (or selectors) that you want to limit the scope of the style declarations to, followed by a set of curly braces {} containing those declarations. Here's a basic example:

@scope .my-component {
  .title {
    font-size: 2em;
    color: blue;
  }
}

In this example, the .title class will only apply to elements that are descendants of any element with the .my-component class. This is great for component-based design where you want to limit the reach of your styles.

When to Use @scope?

The @scope rule is especially useful when you're working on large-scale projects with many stylesheets, or when you're building modular components. By using @scope, you can ensure that styles specific to a module or component don't unintentionally affect other parts of your site. This brings about a clear separation of concerns in your CSS.

Example of @scope in Action

Here's a more complex example to illustrate how @scope can be beneficial:

<div class="module1">
  <h1 class="title">Module 1 Title</h1>
  <p class="text">This is some text for Module 1.</p>
</div>
<div class="module2">
  <h1 class="title">Module 2 Title</h1>
  <p class="text">This is some text for Module 2.</p>
</div>
@scope .module1 {
  .title {
    color: red;
  }
  .text {
    color: blue;
  }
}
@scope .module2 {
  .title {
    color: green;
  }
  .text {
    color: purple;
  }
}

In this example, the .title in .module1 will be red and the .text will be blue, while in .module2, the .title will be green and the .text will be purple. Without @scope, you would need to create separate class names for the title and text of each module to achieve the same effect.

Lots more information available on @scope in this proposal and explainer.