Introduction
The :root
CSS pseudo-class matches the root element of a tree representing the document. In HTML, :root
represents the <html>
element and is identical to the selector html
, except that its specificity is higher.
/* Selects the root element of the document:
<html> in the case of HTML */
:root {
background: yellow;
}
:root {
--main-bg-color: hotpink;
--pane-padding: 5px 42px;
}
.one {
color: white;
background-color: var(--main-bg-color);
margin: 10px;
width: 50px;
height: 50px;
display: inline-block;
}
Inheritance of custom properties
Custom properties do inherit. This means that if no value is set for a custom property on a given element, the value of its parent is used. Take this HTML:
<div class="one">
<div class="two">
<div class="three"></div>
<div class="four"></div>
</div>
</div>
… with the following CSS:
.two {
--test: 10px;
}
.three {
--test: 2em;
}
In this case, the results of var(--test)
are:
- For the
class="two"
element:10px
- For the
class="three"
element:2em
- For the
class="four"
element:10px
(inherited from its parent) - For the
class="one"
element: invalid value, which is the default value of any custom property
Custom property fallback values
.two {
/* Red if --my-var is not defined */
color: var(--my-var, red);
}
.three {
/* pink if --my-var and --my-background are not defined */
background-color: var(--my-var, var(--my-background, pink));
}
.three {
/* Invalid: "--my-background, pink" */
background-color: var(--my-var, --my-background, pink);
}