dimal
dimal
KPCKevin Powell - Community
Created by dimal on 9/14/2024 in #front-end
How to achieve BEM / CSS Module type scoping with @scope
I'm trying to wrap my head around how @scope works and specifically how to implement parent/child scoping like in BEM or CSS Modules, where you can write styles that apply to a component that won't bleed into any child components. I thought that's what to was for, but it seems like it doesn't always do what I'd hoped. This works as expected. "Outer Text" is red. "Inner Text" is black.
<style>
@scope (.outer) to (.child) {
.text {
color: red;
}
}
</style>

<div class="outer">
<div class="text">Outer Text</div>

<div class="child">
<div class="text">Inner Text</div>
</div>
</div>
<style>
@scope (.outer) to (.child) {
.text {
color: red;
}
}
</style>

<div class="outer">
<div class="text">Outer Text</div>

<div class="child">
<div class="text">Inner Text</div>
</div>
</div>
But this doesn't do what I'd expect. Both "Outer Text 2" and "Inner Text 2" are purple.
<style>
@scope (.outer-2) to (.inner-2) {
:scope {
color: purple;
}
}
</style>

<div class="outer-2">
Outer Text 2

<div class="inner-2">Inner Text 2</div>
</div>
<style>
@scope (.outer-2) to (.inner-2) {
:scope {
color: purple;
}
}
</style>

<div class="outer-2">
Outer Text 2

<div class="inner-2">Inner Text 2</div>
</div>
Am I missing something here? According to the spec it seems like :scope should not include .inner-2?
https://drafts.csswg.org/css-cascade-6/#example-f310c4e4
3 replies