References

Beginner-friendly references for web development, with live, editable examples.

The CSS :root selector

Selector CSS All modern browsers Updated
Quick answer

The CSS :root selector matches the root element of the document — the <html> element. It behaves like html but with higher specificity, and it is the conventional place to declare global custom properties (CSS variables) so they are available everywhere on the page.

Overview

:root selects the very top of the document tree — in HTML, that is always the <html> element. It matches the same element as the html selector, but as a pseudo-class it carries slightly higher specificity, which is occasionally useful.

By far its most common use is as the home for global custom properties. Declaring your design tokens on :root:root { --brand: #1c7ce9; --space: 16px; } — makes them inherit down to every element on the page, so var(--brand) works anywhere. This is the standard setup for theming, and redefining those tokens inside a dark-mode media query re-themes the whole site.

You will sometimes see :root used to set a base font size or the color-scheme too. As a rule of thumb: if a value should be global, :root is where it goes.

Syntax

/* global design tokens */
:root {
  --brand: #1c7ce9;
  --space: 16px;
  color-scheme: light dark;
}

Example

Live example
<style>
  :root { --brand: #6d28d9; }
  .badge { background: var(--brand); color: #fff; padding: 12px 18px; border-radius: 8px; font: 600 14px system-ui, sans-serif; display: inline-block; }
</style>
<div class="badge">My color comes from a token on :root</div>

Best practices

  • Declare global custom properties on :root so they are available everywhere.
  • Redefine those tokens inside @media (prefers-color-scheme: dark) for an easy site-wide dark mode.
  • Use it for genuinely global values — base font size, theme tokens, color-scheme — not for ordinary styling.
  • Prefer :root over html for variables by convention, though both target the same element.

Frequently asked questions

What does :root match in CSS?
The root element of the document, which in HTML is the <html> element.
Why declare CSS variables on :root?
Because they then inherit down to every element, making the tokens available across the whole page via var().
What is the difference between :root and html?
They match the same element, but :root has higher specificity. By convention, custom properties are declared on :root.
How do I set up dark mode with :root?
Declare your color tokens on :root, then redefine them inside @media (prefers-color-scheme: dark).