What is the css / html `root` element?

Viewed 30949

I have just recently started using NetBeans IDE (6.9.1) and have used it to add a stylesheet to my site-in-progress.

To my surprise, one element was automatically added:

root { 
    display: block;
}

Looking around, I could find some information about the :root pseudo-class but nothing about the root element itself.

What is the root element and does it have any use?

7 Answers

:root can be used to declare CSS variables

in case anyone finds this old question and needs the information, :root is often used in examples to declare CSS Custom Properties or "variables" that become available throughout the document, for example:

    :root {
      --darkGreen: #051;
      --myPink: #fce;
    }
    
    section {
      color: var(--darkGreen);
      background: var(--myPink);
    }

    article h3 {
      color: var(--darkGreen);
    }

However, any element can be used as the selector for CSS variables (not just :root) so html or body will also enable any element on the page to access them. If anyone has a good reason for using :root, I'd like to know it.

References:

The :root selector allows you to target the highest-level “parent” element in the DOM, or document tree. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

In the overwhelming majority of cases you’re likely to encounter, :root refers to the <html> element in a webpage. In an HTML document the html element will always be the highest-level parent, so the behaviour of :root is predictable. However, since CSS is a styling language that can be used with other document formats, such as SVG and XML, the :root pseudo-class can refer to different elements in those cases. Regardless of the markup language, :root will always select the document’s top-most element in the document tree.

Related