Custom Properties: Questioning â:rootâ
Published on Sep 21, 2020 (updated Aug 31, 2021), filed under development, css (feed). (Share this on Mastodon or Bluesky?)
For custom properties (aka CSS variables) we got into the habit of declaring variables in a rule with a :root
selector.
This habit we probably inherited from the spec, and it had then likely been picked up and promoted by the larger web development communities.
Hereâs a basic example of :root
in action:
:root {
--test: green;
}
body {
background: var(--test);
}
Whatâs interesting about this use of :root
is how rarely CSS is otherwise used to style non-HTML documentsâwhose targeting is :root
âs main selling point. Ask yourself, when have you last styled anything not HTML or SVG? (I did until 2009, for RSS feeds.)
Whatâs also interesting is how much emphasis is usually put on avoiding the universal selector, yet adding classes to everything.
All of this is rather ironic, and makes :root
for custom properties look like a somewhat âhipsterâ response, when one had just found out that CSS can be used for languages other than HTML. No offense thereâit just looks a little like someone had just found out. At this point many may be following a convention.
Use of :root
for custom properties goes beyond irony, however, when itâs used exclusively for HTML. There the enthusiasm seems out of place:
The root element for HTML is <html>
. That is well-known. If a web developer knows what theyâre stylingâif you know what youâre stylingâ, be specific. That means, use html
as your selector, not :root
. It works:
html {
--test: green;
}
body {
background: var(--test);
}
Therefore, unless youâre working in an environment in which style sheets serve several document types (and roots) at the same time, question the use of :root
, for custom properties. It could be argued to be an anti-pattern for HTML. Be specific.
Many thanks to Hannes Schluchtmann for reviewing this post.
About Me
Iâm Jens (long: Jens Oliver Meiert), and Iâm a web developer, manager, and author. Iâve been working as a technical lead and engineering manager for companies youâve never heard of and companies you use every day, Iâm an occasional contributor to web standards (like HTML, CSS, WCAG), and I write and review books for OâReilly and Frontend Dogma.
I love trying things, not only in web development and engineering management, but also in other areas like philosophy. Here on meiert.com I share some of my experiences and views. (I value you being critical, interpreting charitably, and giving feedback.)