:root

Term side of the Card.
Topic: Pseudo Classes
Unit title: :root
Categories: Pseudo-class
Explanation side of the Card

Explanation: The pseudo-class that targets the highest-level parent of the document, typically the `<html>` element. It's often used to define global CSS variables that can be accessed throughout the entire stylesheet, making it easier to manage consistent design values.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.
  • The safari browser supports this feature starting from version 1.
Availability: 

Example

Wrongcss
body {
  --text: #222;
}
html {
  color: var(--text);
}
Rightcss
:root {
  --text: #222;
  color: var(--text);
}

Custom properties inherit downward, so tokens on :root are visible everywhere, including the html element.

Common mistakes

  • An html rule losing to a :root rule, because :root has class-level specificity.
  • Defining custom properties on body, so html-level styles can't read them.

Key points

  • Global design tokens are declared on :root, like :root { --brand: #0055ff; }.
  • Theme overrides use :root[data-theme='dark'] or a prefers-color-scheme media query.

Interview questions

Is :root the same as html?

In HTML documents they match the same element, but :root has higher specificity, like a class.

Why are CSS variables defined on :root?

Because :root is the top element, so every element in the page inherits its custom properties.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy