CSS :root
Pseudo-Class
The :root
pseudo-class represents the highest-level parent element in the document (the <html>
element in HTML). It is commonly used to define CSS variables and apply styles globally.
1. Syntax
Example:
2. What Makes :root
Special?
-
It targets the
<html>
element, but with higher specificity thanhtml {}
. -
It is useful for defining CSS variables (
--custom-property
). -
It helps maintain consistency across a website.
3. Example – Using :root
for CSS Variables
✅ Benefits of this approach:
✔ Makes theme updates easier.
✔ Ensures a consistent color scheme.
✔ Helps create light & dark themes dynamically.
4. Example – Dark Mode Toggle using :root
✅ A simple dark mode switch using CSS variables.
5. Example – Responsive Font Size with :root
✅ This automatically scales font size for different screen sizes.
6. :root
vs html {}
– What's the Difference?
Feature | :root | html {} |
---|---|---|
Represents | <html> element | <html> element |
Specificity | Higher | Lower |
Common Use | CSS Variables, Theming | Basic styling |
Overrides | Can override html {} styles | Lower priority |
7. Browser Support
✅ Works in all major browsers, including Chrome, Firefox, Edge, Safari, and even Internet Explorer 11.
8. Best Practices
✔ Use :root
only for global values like CSS variables, themes, or global properties.
✔ Don’t use :root
for normal styling—use html
or body
instead.
✔ Combine :root
with CSS variables for flexible styling.