You really don’t have to put your CSS custom properties in :root {}

Chris Coyier Chris Coyier on

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.

Wanna learn modern CSS layout?

Frontend Masters logo

We have an in-depth course on Advanced CSS Layouts that digs into the big stuff like grid and flexbox, and then more like custom properties and calc(), using them for advanced layouts and practical solutions.

7-Day Free Trial

Leave a Reply

Your email address will not be published. Required fields are marked *

$839,000

Frontend Masters donates to open source projects through thanks.dev and Open Collective, as well as donates to non-profits like The Last Mile, Annie Canons, and Vets Who Code.