CSS :root Selector (vs. html) by Example

CSS :root Selector (vs. html) by Example

The :root selector in CSS lets you matches the most top-level element of your document (or the document root). In the case of HTML, this is equivalent to using the html selector to select the <html> element, with the exception that the :root selector has a higher specifity (:root is a pseudo-class selector which has a specifity equals to a class selector).

CSS is not just for styling HTML documents. It can be used with other document languages, such as SVG and XML--the :root pseudo-class, in this case, refers to different elements.

We can use the :root pseudo-class selector can be used like any other selector. For example:

:root {
  background: hsl(0, 100%, 50%);
  color: blue;
}

This will apply the CSS styles to the <html> element.

The :root Selector vs. the html Selector

The major difference between :root and html is that :root (which is a pseudo-class selector) has a higher specificity than html ( wihc is a type selector). Let's consider this small example:

:root {
  background-color: white;
}
html {
  background-color: black;
}

Using :root with CSS Variables (Custom properties)

The :root selector overrides the html selector. The color of the background will be white not black.

One useful use of the :root selector is for declaring global-scope CSS variables or custom properties. For example:

:root { --bg-color: hsl(120, 100%, 50%); }

The --bg-color custom property is available on the global scope. That means the value of --bg-color which is hsl(120, 100%, 50%); can be accessed from any other DOM element. We can use the var() function to get the value:

#main{
    background-color: var(--bg-color);
}

The color of the background will be hsl(120, 100%, 50%);.

References


  • Date: