How to Use the CSS :root Pseudo-Class Selector
Table of Contents
Learn about the CSS :root
pseudo-class selector, and how you might want to use it in your projects!
The CSS :root
pseudo-class selector is used to select the highest-level parent of a given specification. In the HTML specification, the :root
is essentially equivalent to the html
selector.
In the CSS snippet below the :root
and html
styles will do the same thing:
:root {
background-color: gray;
}
html {
background-color: gray;
}
If you noticed I said :root
is essentially equivalent to the html
selector. In fact, the :root
selector has more authority than html
. This is because it’s actually considered a pseudo-class selector (like :first-child
or :hover
).
As a pseudo-class selector, it has more authority/higher specificity than tag selectors:
:root {
background-color: blue;
color: white;
}
html {
background-color: red;
color: white;
}
Despite the html
selector coming after, the :root
selector still wins, thanks to its higher specificity!
Cross-Specification #
In the HTML specification, the :root
pseudo-class targets the highest-level parent: html
.
Since CSS is also designed for SVG and XML you can actually use :root
and it will just correspond to a different element.
For example, in SVG the highest-level parent is the svg
tag.
:root {
fill: gold;
}
svg {
fill: gold;
}
Similar to HTML, the :root
and svg
tags select the same element, however the :root
selector will have higher specificity.
Practical Uses #
What are the practical uses for :root
? As we covered earlier, it’s a safe substitute for the html
selector.
This means you can do anything you’d normally do with the html
selector:
:root {
margin: 0;
padding: 0;
color: #0000FF;
font-family: "Helvetica", "Arial", sans-serif;
line-height: 1.5;
}
If you’d like, you can refactor this code to use CSS Custom Properties to create variables at the global level!
:root {
margin: 0;
padding: 0;
--primary-color: #0000FF;
--body-fonts: "Helvetica", "Arial", sans-serif;
--line-height: 1.5;
}
p {
color: var(--primary-color);
font-family: var(--body-fonts);
line-height: var(--line-height);
}
The added benefit of using :root
instead of html
is that you can style your SVG graphics! 🤯
:root {
margin: 0;
padding: 0;
--primary-color: #0000FF;
--body-fonts: "Helvetica", "Arial", sans-serif;
--line-height: 1.5;
}
svg {
font-family: var(--body-fonts);
}
svg circle {
fill: var(--primary-color);
}
For extensive documentation on the :root
pseudo-class selector, visit the Mozilla Developer Network