88

I can't seem to find much information about this.

Smashing Magazine seems to be saying that html and :root are the same thing but surely there must be a tiny difference?

Ed The ''Pro''
  • 875
  • 10
  • 22
suryanaga
  • 3,728
  • 11
  • 36
  • 47

4 Answers4

130

One technical difference between them is that :root - being a pseudo class has a greater specificity than html (a type selector)

:root {
  color: red
}
html {
  color: green;
}
<div>hello world</div>

So, in the above example, the :root selector overrides the html selector and the text appears red.

Danield
  • 121,619
  • 37
  • 226
  • 255
  • 3
    one interesting difference is that other pseudo class (like `:after`) won't be affected by `:root`. On the other hand specifying `html` make sure that everything within the `html` tag is affected even the other pseudo class. – Pierrick Rambaud Oct 07 '22 at 10:18
127

From the W3C wiki:

The :root pseudo-class represents an element that is the root of the document. In HTML, this is always the HTML element.

CSS is a general purpose styling language. It can be used with other document types, not only with HTML, it can be used with SVG for example.

From the specification (emphasis mine):

This specification defines Cascading Style Sheets, level 2 revision 1 (CSS 2.1). CSS 2.1 is a style sheet language that allows authors and users to attach style (e.g., fonts and spacing) to structured documents (e.g., HTML documents and XML applications).

DrCord
  • 3,917
  • 3
  • 34
  • 47
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
37

For HTML documents, there is no difference - your root element is the <html> tag, so html{} and :root{} are (besides from a difference in specificity) semantically equivalent.

However, you can apply CSS not only to HTML, but all XML-like documents. That's why :root is there - to target the document's root element regardless of document type. Most people are confused by the difference because the overwhelmingly predominant use case for CSS is styling HTML documents.

Example: You can style SVG documents with CSS. When styling it, your root element will (obviously;-)) not be html but svg. See the following list of SVG tags.

Christoph
  • 50,121
  • 21
  • 99
  • 128
1

Another thing to consider is that it's technically possible to replace the root element using javascript:

<html>
<body>
  <div id=test>
      This will become the root element!
      <style>
        :root { text-decoration: underline; }
        html { color: red; } /* this selector will stop working */
      </style>
  </div>
  <button onclick=document.documentElement.replaceWith(test)>click to replace the root</button>
</body>
</html>
12Me21
  • 992
  • 10
  • 22