What the :root Pseudo Class is and Why You Might Use it

April 07, 2014 | 3 Minute Read

The :root pseudo class, at first glance, is a little odd. It seems like it's simply a replacement for using the HTML tag as a CSS selector. There's a little bit more to it than that and in this article I will explain what the :root pseudo class is and why you might use it.

What’s Different Between :root and html?

For the most part the :root pseudo class will be referring to the html element. :root is the outer most or root element of the document which will always be the HTML tag when styling an HTML document.

The main difference between the two is that when styling HTML, SVG, or XML :root will refer to the outer most parent element of the document where as HTML is simply a CSS element selector that will always match the HTML tag. When using CSS to style SVG or XML files the root element will match whatever the parent node is within those files.

Another difference you should keep in mind when using :root is that it will have a higher specificity than HTML. :root will have a calculated specificity of 0 0 1 0 while HTML will have a specificity of 0 0 0 1. You can see this calculation in action using this handy specificity calculator by Keegan Street.

Some Examples

To better illustrate the differences I’ve provided a couple of examples below.

In an HTML Document

This is an example using :root in an HTML document where it will target the html tag.

:root { 
    background-color: red; 
}

See the Pen Untitled by Brian (@brianmtreese) on CodePen.

In an SVG

This is an example using :root in an embedded SVG in which it will target the outer svg tag.

<style media="screen">
    <![CDATA[ :root { background-color: #33cccc !important; }]]>
</style>

See the Pen Untitled by Brian (@brianmtreese) on CodePen.

In Conclusion

I’ve heard some people mention that you should actually be using :root instead of HTML by default now. I’m not sure if I’m sold on this yet but it does make sense if you consider the future of Web Components. Besides SVG and XML, Web Components will also use CSS. They will allow us to encapsulate modules of markup, functionality, and style into their own components. Using :root would allow us to easily target the root of those elements regardless of what their outer most tag is.


Browser Support

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 1 and above

The CSS :root pseudo class has pretty good browser support working in all modern browsers. Not supported in ie8 and below.


Sources

Found any of this Stuff Helpful?

If you found any this helpful and want to show some love, you can always buy me a coffee!