How to achieve BEM / CSS Module type scoping with @scope
I'm trying to wrap my head around how
https://drafts.csswg.org/css-cascade-6/#example-f310c4e4
@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.
But this doesn't do what I'd expect. Both "Outer Text 2" and "Inner Text 2" are purple.
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
@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! 🙂Oh, duh! 🤦♂️ Thanks @nilaallj! I shouldn't have used an inheritable property for my tests!