CSS :root Pseudo-Class Selector

Posted on Updated on HTML by Adam Laki

The :root selector is an interesting one which helps us to select our document’s root element.

In HTML, our root element is always thetag, so in this case, it is something that doesn’t add too much to our work but still not a bad idea.

In other XML based documents like in an SVG, it has more purpose because the root element can be different.

The :root vs the html Selector

The :root has a higher specificity so it can override any html element declaration because it is a pseudo-class selector.

:root {
    background-color: blue;
}

html {
    background-color: red;
}

/* Our background's color will be blue because the :root selector has a higher specificity. */

The pseudo-class selector also is the newer one so the support is less than a simple element selector. But this is only true if you have to support the really old browsers.

Declare the Variables at the Root

One place where you could always meet the :root selector is the declaration of the custom properties. It is some convention to declare our global variables using this selector instead of the HTML. Sure it can tell more about the intention, but the result will be the same if we use the html element selector.

:root { 
    --bg-color: #fff;
    --text-color: #676767;
}

Should We Use the :root Selector

As always, it is something that depends on your workflow. Right now, in the case of an HTML document, it doesn’t add any plus. But still, it can be a good convention if you use it consequently. Besides this, it is a nice to know selector.

Need a web developer? Maybe we can help, get in touch!