An introduction to @scope

In CSS, @scope is a new at-rule that allows you to define a scope for your styles, meaning you can limit the application of certain styles to specific parts of your HTML. This is useful for avoiding conflicts and ensuring that styles do not unintentionally affect elements outside their intended section. For example, if you want certain styles to apply only within a specific section of your webpage, you can wrap those styles in an @scope block, specifying the container element. This way, the styles within the @scope block will only apply to elements inside the specified container, making your CSS more modular and easier to manage.


In your CSS file, you can use the @scope rule to apply styles specifically to elements within each section:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@scope Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="section1">
        <p>This is section 1.</p>
    </div>
    <div id="section2">
        <p>This is section 2.</p>
    </div>
</body>
</html>


In this example:

@scope (#section1) {
    p {
        color: blue;
        font-size: 20px;
    }
}


@scope (#section2) {
    p {
        color: green;
        font-size: 16px;
    }
}


  • The @scope (#section1) block applies the styles (blue text color and 20px font size) only to the <p> elements inside the <div> with the id="section1".
  • The @scope (#section2) block applies different styles (green text color and 16px font size) only to the <p> elements inside the <div> with the id="section2".


This means the paragraph in section1 will be blue and larger, while the paragraph in section2 will be green and slightly smaller. The @scope rule helps keep styles contained and prevents them from affecting other parts of your webpage.