DEV Community

Understanding the Concept of Scoping in CSS

Bilkeesu Babangida on September 29, 2024

Introduction One of the key problems developers face with CSS is styles leaking out to components they should not apply to. Developers h...
Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Really nice article, and also very complete, although some of the details like the & working like the scope root selector while :root only selects the root specifically might be hard to understand when you don't already know them.

One thing I'd add: it'll also be possible to scope styles in an @import statement and even in <link> tags, although the details of this are still being discussed.

github.com/w3c/csswg-drafts/issues...

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

I just remembered that I wrote my own article on scope a few years ago; it's not nearly as detailed as this one, but it mentions a few additional details about where this could be useful to add some more context:

dev.to/darkwiiplayer/what-is-css-s...

Collapse
 
best_codes profile image
Best Codes

Very interesting! You can achieve the same thing much more succinctly, like this:

.box {
  display: flex
}

.box .p {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

In that example, only <p> elements in an element with class box would be red, the rest would be the default color.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

This only works for the simplest cases. It doesn't consider scope proximity and, more importantly, doesn't let you define a lower boundary for the scope.

Collapse
 
annavi11arrea1 profile image
Anna Villarreal

css scope is interesting. Haven't used it yet. thanks for sharing! i'll have to try it out.

Collapse
 
bilkeesu96 profile image
Bilkeesu Babangida

Thank you for the feedback. You should try it out soon ☺️

Collapse
 
annavi11arrea1 profile image
Anna Villarreal

Here is my full response. I tagged your post btw! dev.to/annavi11arrea1/styling-choi...

Thread Thread
 
bilkeesu96 profile image
Bilkeesu Babangida

Thank you for the tag. I enjoyed reading your response 😊

Thread Thread
 
annavi11arrea1 profile image
Anna Villarreal

Thank you!

Collapse
 
annavi11arrea1 profile image
Anna Villarreal

I intend to! you sparked a train of thought and i am now writing LOL

Collapse
 
kurealnum profile image
Oscar

Great post!

Collapse
 
bilkeesu96 profile image
Bilkeesu Babangida

Thank you 😊