- read

Chrome 118: CSS @scope Rules Are Coming!

Xiuer Old 46

Chrome 118: CSS @scope Rules Are Coming!

Xiuer Old
JavaScript in Plain English
4 min read1 day ago

--

CSS @scope rules

@scope at-rule allows us to limit style rules to a given range and style elements based on proximity to this range.

Let’s look at an example first:

<div class="outer">
<p>medium</p>
<div class="inner">
<p>Xiuer Old</p>
</div>
</div>

In @scope the absence of , the rule applied is the last declared style.

.inner p {
color: goldenrod;
}

.outer p {
color: green;
}

So the styles of both P tags are like this:

Using @scope, nested styles can be written, and we can override styles based on proximity:

@scope (.inner) {
p {
color: goldenrod;
}
}

@scope (.outer) {
p {
color: green;
}
}

Also, @scope it saves us from writing long and complex class names and makes it easy to manage larger projects and avoid naming conflicts.

When there is no @scope:

<div class="first-box">
<h1 class="first-box__main-content"> medium </h1>
</div>
<div class="second-box">
<h1 class="second-box__main-content"> Xiuer Old </h1>
</div>
.first-box__main-content {
color: red;
}

.second-box__main-content {
color: green;
}
<div class="first-box">
<h1 class="main-content"> medium </h1>
</div>
<div class="second-box">
<h1 class="main-content"> Xiuer Old </h1>
</div>

Use @scope:

@scope(.first-box){
.main-content {
color: grey;
}
}
@scope(.second-box){
.main-content {
color: mediumturquoise;
}
}

Added two new media queries

Chrome the new version adds two detection values ​​that adapt to different user preferences and device conditions…