I feel like most usage of global CSS custom property use has the author putting them into a :root
selector like:
:root {
--brand-color: red;
}
Code language: CSS (css)
This is just a PSA that you… don’t have to. It’s not required. It has nothing to do with custom properties. It’s just a selector. It happens to select the html
element on a website, except for with extra specificity that I’d wager isn’t typically useful. I think the earliest code samples of them in the spec did it that way for whatever reason, and it stuck as a weird niche cultural artifact.
Well (you shake your dirty martini at me) Chris — I just prefer :root
because not all CSS usage is within an HTML website. You can put a <style>
tag in <svg>
you know!!!
Yes, and if you do that, :root
will still select the html
element, not the “root” of the <svg>
element. So that’s weird. It’s true that if you do SVG-as-<img>
it will select the root of the SVG, but that difference in behavior is probably reason enough not to do it.
Anyway — just quit being fancy and use the html
element.
One thing that keeps me using
:root
is that sure, it’s gonna be<html>
99% of the time, but what happens if we’re in the shadow DOM if we do that?Just feels safer and dare I say, scalable.
I don’t think
:root
does anything in a shadow dom web component though??https://codepen.io/chriscoyier/pen/WbQJKge
It’s
:host
that kinda selects the “root” of a web component.“quit being fancy” lol no I don’t think that I shall