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
2 Replies
nilaallj
nilaallj3mo ago
@scope provides selector isolation, not style isolation. This means that color and other inheritable properties still reaches beyond the scope limit. That is expected and according to the specification. You get this problem in your second example because the inner element still inherits normally from its ancestors. When using @scope it often makes sense to only declare inheritable values on very generic selectors, such as p, span, h2, figcaption etc. Or on wrappers that doesn’t have descendants beyond the scope limit. Hope it helps! 🙂
dimal
dimalOP3mo ago
Oh, duh! 🤦‍♂️ Thanks @nilaallj! I shouldn't have used an inheritable property for my tests!
Want results from more Discord servers?
Add your server