Is there anything wrong with defining custom variables in html instead of :root?
I just think it's neater to make "global variables" in the context of the html selector, but I seem to only ever see examples that use :root. I thought they were the same thing in a web page so why not in html?
5 Replies
Theāhttps://developer.mozilla.org/en-US/docs/Web/CSS/:root They're almost the same thing, but:root
CSS pseudo-class matches the root element of a tree representing the document. In HTML,:root
represents the<html>
element and is identical to the selector html, except that its specificity is higher.
:root
has a higher specificity so any variables declared there over-write any in html
.
In addition, :root
is the root element of any document, so could be used for SVGs, XML, etc. So if you did, for example, inline styles for an SVG image and used html
as the place for global variables it wouldn't work since there is no html
element in an SVG.Another option is locally defined variables.
Easier to tweak with js for example.
Using local variables is the opposite of setting global ones, though. And doesn't answer the OPs question at all.
But it does give context to how custom variables can be used.
Thanks for the feedback š
To add to this, Chrome did a lot of optimizations for custom properties that are declared on
:root
.
This was at least 18 months ago, so there are possibilities that those optmizations have made it to other selectors as well, but I have no info there.
I need to make some friends with pople on the browser teams, instead of knowing people who know them, lol.