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?

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

  1. Andy Bell says:

    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.

  2. Joshua Byrd says:

    “quit being fancy” lol no I don’t think that I shall

Leave a Reply

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

$966,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.