CSS @scope Alternative

February 17, 2024

With CSS @scope recent development, it may take a while for other browsers to pick up. Meanwhile, you may need something that works the same way.

The alternative for CSS @scope is no other than specificity. But it could be difficult to keep track of unique classes without a help from a tool of some kind.

So here's a tips: you could try keeping a scope ID counter somewhere in your site code. Then, everytime you need to scope a style on a container, you can increase the counter.

html
<!-- scope counter : 0 -->

[ .widget data-scope-id="0"

  <!-- sc-0 is scope ID: 0 -->
  [ .title .sc-0] 

]

This way you can keep the class name short and easily recognize a scoped style container.

Drawbacks

1. You should only increase the counter by time so to make sure there's never a conflicted class scope.

2. Using CSS wrapping is good enough, but you are now forced to add an ampersand (&) prefix for each child selectors.

css
.widget .sc-0 {
  
  &.title {
    background: yellow;
  }
  
}

Comments

Thank You

for your visit