CSS :root Selector
The :root selector is a CSS pseudo-class that matches the root element of the document. In an HTML document, this is the <html> element.
While it behaves similarly to the html selector, the :root selector has higher specificity and is commonly used to define global styles or CSS custom properties (variables).
Syntax:
:root {
/* CSS properties */
background-color: lightgray;
font-size: 16px;
}
The styles defined within the :root block will apply to the entire document unless overridden by more specific rules.
Basic Usage Examples
Example 1: Applying a Global Background Color
The following example sets the background color for the entire document using the :root selector:
<!DOCTYPE html>
<html>
<head>
<title>root selector</title>
<style>
:root {
background: green;
}
body {
text-align: center;
}
h1 {
color: white;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>:root selector</h2>
<p>The root of document is body tag</p>
</body>
</html>
Output:
Using the :root Selector for CSS Variables
The :root selector is particularly useful for defining CSS custom properties (variables), which can be used throughout the entire stylesheet for consistent theming.
Example: Defining and Using CSS Variables
<!DOCTYPE html>
<html>
<head>
<title>Using CSS Variables with :root</title>
<style>
:root {
--main-bg-color: #f0f0f0;
--main-text-color: #333;
--primary-color: #4CAF50;
--font-size: 18px;
}
body {
background-color: var(--main-bg-color);
color: var(--main-text-color);
font-size: var(--font-size);
}
button {
background-color: var(--primary-color);
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}
button:hover {
background-color: darkgreen;
}
</style>
</head>
<body>
<h1>Themed Webpage Using :root</h1>
<button>Click Me</button>
</body>
</html>
Output:

Supported Browsers:
The browser supported by :root selector are listed below:
- Apple Safari 1.0 and above
- Google Chrome 1.0 and above
- Edge 12.0 and above
- Firefox 1.0 and above
- Opera 9.5 and above