DEV Community

Discussion on: CSS VARIABLE SCOPE

Collapse
 
kodekage profile image
Prosper Opara

A variable declared within :root is only accessible to it and its children. Other elements outside of :root will not have access to the variable unless they are re-declared in this element.

But what if we can declare a variable once with a GLOBAL SCOPE, such that it's not bound to any :root element and its children, but can be easily accessed by every other element regardless of their position(in or outside the :root element).

Collapse
 
equinusocio profile image
Mattia Astorino • Edited

In HTML there can't be anything outside the document root element, it is always the <html> tag.

I think you don't know CSS Properties and Values API Level 1. Registering custom properties by CSS you must bind it to a selector since in css you can't write nothing outside {}. Since in CSS :root {} is the document root element (<html>) it works as a "global scope" because there is nothing outside it. So any custom property declarede at :root level is accessible by the entire document.

BTW, right now you can also register custom properties directly to the document object through JS using Houdini api...

  1. Let property set be the value of the current global object’s associated Document’s
CSS.registerProperty({
    name: "--my-color",
    syntax: "<color>",
    inherits: false,
    initialValue: "rgba(0,0,0,0)"
});

There is also a postcss plugin that allows you (trying to bring a lv2 proposal) to do the reverse thing, register a document-level custom property inside CSS:

github.com/jonathantneal/postcss-r...

@property --theme {
  syntax: '<color>+';
  initial-value: #fff;
  inherits: true;
}
Thread Thread
 
kodekage profile image
Prosper Opara

Ok, i get your point now, html{} is the solution.

Thanks for sharing your knowledge about CSS internals.