使用:root CSS选择器而不是html CSS选择器有什么好处?

In HTML documents the :root pseudo-class selector introduced in CSS3 is equal to html selector, with the only difference is that :root has a higher specificity. If they are almost the same, then what are the practical benefits of using html?

I have read that :root selector is useful for declaring a global CSS variable, i.e. a variable accessible in the whole HTML code. However I can set a variable using html selector, and it will be available in the whole HTML code as well. The only benefit I found on https://alligator.io/css/root-pseudo-class/ is that a CSS variable set in :root can also be used to style SVG graphics. Is it the only benefit?

评论
  • 万伶伶
    万伶伶 回复

    You pretty-much answered your own question with the last bit about :root matching both <html> and <svg> - or any other root element in non-HTML documents.

    Remember that CSS is also designed to be compatible with more than just HTML and SVG, it's also designed to be compatible with XML, and with XML the root element might share the same element-name as a child-element - so this is a way to work with those kinds of documents because CSS offers no other way of selecting only the root element for styling, so it's in the same family as :first-child, :first-of-type, :last-of-type, etc.

    I'll add there's also the risk that a malformed HTML document might have an illegal <html> element located elsewhere in the DOM. If you use just html as a selector then those additional <html> elements will also be styled, which would break your site's layout if you have the commonplace html { min-height: 100%; height: 100%; } rule. Changing it to html:root { ... } fixes that.