CSS :root Selector
CSS :root selector in CSS is a pseudo-class that matches the root element of a document tree. In the case of HTML documents, :root represents the <html> element itself, so this selector is identical to the html element selector. But the :root selector have more specificity than HTML element selector.
Syntax
/* Selects the root element (<html>) of the document */
:root {
// css variable declarations or properties
}
Declaring Global CSS variables
The main purpose of root selector is to declare variables in CSS. This will have a global access across every selectors in the stylesheet. Lets see an example.
Example
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--main-color: blue;
--secondary-color: white;
}
body {
background-color: var(--main-color);
}
h1 {
color: var(--secondary-color);
}
</style>
</head>
<body>
<h1>Welcome to CSS Root Example</h1>
<p>
This is an example of using CSS root to define and use
custom CSS variables.
</p>
</body>
</html>
Supported Browsers
| Selector | ![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|---|
| :root | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
css_properties_reference.htm
Advertisements




