Home > Enterprise >  Scoped CSS doesn't work and the styles get leaked out
Scoped CSS doesn't work and the styles get leaked out

Time:04-15

I have a CSS file called "stylesheet.css"

p {
    margin: 0%;
    font-family: cursive;
    font-size: 1cm;
}

h1 {
   font-family: sans-serif;
}

And I have an html file in the same folder

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Test</title>
    </head>
    <body>
        <p>Test</p>
        <h1>Test</h1>

        <div>
            <style scoped>
                @import "stylesheet.css";
            </style>
            <p>Test (Supposed to be bigger and different font)</p>
            <h1>Test (Should have a different font)</h1>
        </div>
    </body>
</html>

But for some reason, the style rules that I had imported in a scoped style tag in a div leaks out to the body and styles the p tag above: enter image description here

CodePudding user response:

Browsers do not support scoped which has been deprecated.

Even if they did support it, your CSS is targetting the body element and there isn't a body element inside the div that you are scoping the CSS to (and can't be, since a body element isn't allowed there).

Write your CSS to target the elements you actually have.

#scopeTarget {
  margin: 0%;
  font-family: cursive;
  font-size: 1cm;
}
<p>Test</p>

<div id="scopeTarget">
  <p>Test (Supposed to be bigger and different font)</p>
</div>

  • Related