diff --git a/Web/CSS/What is Scope.md b/Web/CSS/What is Scope.md new file mode 100644 index 0000000..2113892 --- /dev/null +++ b/Web/CSS/What is Scope.md @@ -0,0 +1,116 @@ +--- +title: What is CSS @scope and why should I care? +published: true +description: "A short introduction to the new CSS @scope rule, the history of CSS scoping and what makes it useful for different areas of web-development" +tags: css,scope,components,vanilla +date: 20220316 +--- + +## A brief history of Scoping and CSS + +Scoping CSS to certain regions of the DOM is not a new idea. + +The `scope` attribute for ` +
Red Text
+ +Normal Text
+``` + +Many front-end frameworks implement their own scoping by prefixing CSS rules with IDs and classes and adding those to their HTML output. However, this requires a lot of complexity in the framework and is still brittle. + +Then components came into the browser, in the form of custom elements and shadow-DOM. In fact, one part of shadow-DOM is that all the CSS inside it is scoped. However, it doesn't permit outside CSS to leak inside either. + +## Native Scoping is still on the table + +The exact reason why `scope` was originally abandoned seems a bit fuzzy. Some will tell you it was because browsers didn't want to implement it, others say that it was just about letting web components become a thing, then re-evaluate the need for pure CSS scoping. + +Whatever the case may be, CSS authors still seem to have an interest in scoping being a thing, for a variety of reasons. + +## CSS Scoping Revived: `@scope` + +The `@scope` rule is the newest attempt at bringing CSS scoping to the browser. It is described in the [Working Draft](https://www.w3.org/TR/css-cascade-6/#scoped-styles) of the *CSS Cascading and Inheritance Level 6* specification. + +In other words: it's far from being usable. But there's still plenty of reasons to be hyped about it! 😁 + +----- + +The way this would work is simple: we would first define where we want our rules to apply. We can use any CSS selector here, but to avoid distractions, I will be using the `outer-component` and `inner-component` custom elements for the rest of this article. + +```css +@scope (outer-component) { + p { color: red; } +} +``` + +Any rules written inside this scope block will only apply inside an element described by the selector. + +```html +This text is black
+This text is red
+This text is red
+This text is black
+