:root
is a CSS pseudo-class selector used to select the element that represents the root of the document.
In HTML4, this is always the <html>
element, since it is the highest-level ancestor of all other elements on the page. So, :root
is identical to using the html
as a selector, except that it has a higher specificity.
This means that, in the following example, the styles specified using :root
will override those specified using the html
selector, even if the latter comes next in the style sheet.
:root { /* style the root element */ } html { /* style the root element */ }
In document formats other than HTML, such as SVG and XML, the :root
pseudo-class can refer to another higher-level ancestor.
Trivia & Notes
Just like other pseudo-class selectors, the :root
selector can be chained with other selectors such as :hover
and pseudo-elements such as ::after
, for example, to provide hover styles for the root element in different states. For example, the following will change the background color of the root element when it is hovered:
:root { background-color: #009966; /* smooth the color transition */ transition: background-color .6s; } :root:hover { background-color: #0099ff }
You can see a live demo of this in the Live Demo section below.
Examples
The following will add a content to the root element using the ::after
pseudo-element.
:root::after { content: "I am generated!"; color: white; /* ... */ }
See the live demo below for a live example.
Live Demo
In the following live demo, the root html
element gets a background image, the body gets a green background color, and a purple box is generated and inserted into the html
using the ::after
pseudo-element and centered in the viewport. Note that the pseudo-element does not inherit the styles of the body
because it is not contained inside it—it comes after in in the document.
Browser Support
The :root
pseudo-class selector is supported in Chrome, Firefox, Safari, Opera 9.5+, Internet Explorer 9+, and on Android and iOS.