CSS `:root` Selector: Styling the HTML Root Element
Learn how to use the CSS `:root` selector to efficiently style the root element of your HTML document (). This tutorial explains its higher specificity compared to the `html` selector, demonstrating how to use `:root` for setting global styles and managing CSS precedence effectively.
Using the CSS `:root` Selector
Understanding the `:root` Selector
In CSS, the `:root` selector targets the root element of the HTML document. This is always the <html>
element. While functionally similar to the `html` selector (both target the <html>
element), `:root` has higher specificity. This means that if you apply styles using both `:root` and `html`, the `:root` styles will take precedence (they'll override any conflicting styles set for the html
element).
` :root` Selector Syntax
The syntax is simple; you just use `:root` followed by your CSS rules, enclosed in curly braces:
Syntax
:root {
/* CSS properties and values */
}
Example: `:root` vs. `html` Selector
This example demonstrates the higher specificity of `:root`. Both selectors target the same element, but `:root` overrides conflicting styles set for `html`.
CSS Code
html {
background-color: lightblue; /* This will be overridden by :root */
color: darkblue; /* This will be used because :root doesn't define color */
}
:root {
background-color: lightgreen;
/* color: darkgreen; If this line were uncommented, it would override the html color */
}
In this case, the background color will be light green (from `:root`), but the text color will be dark blue (from `html` because `:root` doesn't specify a text color). If you had also defined a color within the `:root` selector, that color would take priority.