Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Why use the :root pseudo selector to define CSS variables

o my shame, I have found about the CSS :root selector only a few weeks ago when I was changing some styling in the WordPress theme of this blog.

I've seen a piece of code similar to the one below:

:root {
    --color__success: #1fc281;
    --color__info: #00b9f2;
    --color__warning: #f4cc31;
    --color__danger: #e83337;
}

I've recognized the declarations of the CSS variables but what was that :root thing doing there !?

And started to read more about it.

Long story short. The :root is referring to the highest-level parent of a given specification. In the HTML specification, the :root is essentially the same as the html selector.

But, CSS is also designed for SVG. So, we can use :root to select the highest-level parent of a given specification even if is HTML, CSS or XML.

This means that if we want to define global properties, like CSS color variables, we will use :root and those variables will be available both in HTML and SVG.

:root { 
    margin: 0; 
    padding: 0; 
    --main-color: #ff1100; 
}

html {
    color: var(--main-color);
}

svg {
    fill: var(--main-color);
}

And also keep in mind that root is a pseudo selector. This means it will have a higher specificity that the html element selector.

:root { 
    background-color: red; 
    color: white; 
} 
html {
    background-color: red; 
    color: white;
}