CSS :root Pseudo Class

CSS :root Pseudo Class

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

:root { property: value; }

Example:

:root { --primary-color: #3498db; --text-color: #333; }

2. What Makes :root Special?

  • It targets the <html> element, but with higher specificity than html {}.

  • It is useful for defining CSS variables (--custom-property).

  • It helps maintain consistency across a website.

3. Example – Using :root for CSS Variables

:root { --main-bg-color: #f5f5f5; --main-text-color: #222; --accent-color: #ff5733; } body { background-color: var(--main-bg-color); color: var(--main-text-color); } button { background-color: var(--accent-color); color: white; padding: 10px 20px; border: none; cursor: pointer; }

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

:root { --bg-color: white; --text-color: black; } .dark-mode { --bg-color: black; --text-color: white; } body { background-color: var(--bg-color); color: var(--text-color); }
document.body.classList.toggle('dark-mode');

✅ A simple dark mode switch using CSS variables.

5. Example – Responsive Font Size with :root

:root { font-size: 16px; } @media (max-width: 768px) { :root { font-size: 14px; } } p { font-size: 1.2rem; /* Adjusts based on :root font-size */ }

✅ This automatically scales font size for different screen sizes.

6. :root vs html {} – What's the Difference?

Feature:roothtml {}
Represents<html> element<html> element
SpecificityHigherLower
Common UseCSS Variables, ThemingBasic styling
OverridesCan override html {} stylesLower 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close