likes
comments
collection
share

CSS3 的 :root 伪类和 html 有什么区别?

作者站长头像
站长
· 阅读数 31

分类的不同

:root 是伪类选择器。 html 是标签选择器。

:root 并不只适用于 HTML ,它适用于所有 XML 格式文档。 例如使用 CSS 设置 SVG 文档,:root 对应的根元素为 svg

html 适用于 HTML

选择器的级别

根据 W3 文档 中的的描述如下:

PatternRepresentsSectionLevel
Ean element of type E§ 5.1 Type (tag name) selector1
E:rootan E element, root of the document§ 14.1 :root pseudo-class3

html 归类为等级 1 的选择器。 :root 归类为等级 3 的选择器。

样式优先级

MDN文档的解释如下:

The :root CSS pseudo-class matches the root element of a tree representing the document. In HTML, :root represents the <html> element and is identical to the selector html, except that its specificity is higher.

:root 指代的是文档的根节点。 在 HTML 文档中,:root 指代的是 html 根节点。所以,它们两者是相等的。 但是,有一个不同的地方:样式的优先级,:root 的优先级大于 html

现象

data:application/xhtml+xml,<div xmlns="[http://www.w3.org/1999/xhtml](https://link.zhihu.com/?target=http%3A//www.w3.org/1999/xhtml)"><style>:root { background: green; } html { background: red !important; }</style></div>  

在浏览器中打开上述链接,显示的是绿色

可见,即使 html 的 CSS 样式,加了 !important ,也是低于 :root 的优先级。

兼容性

:root 需要 IE9 以上才支持,html 没有兼容性问题。

可替换性

html 根元素,可以使用 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>  

如上述代码所示,当 button 被点击时,html 将会被替换掉。

应用

:root 在 CSS3 中, 一般用于定义全局 CSS 变量

:root {  
  --main-color: hotpink;  
  --pane-padding: 5px 42px;  
}  

参考


坚持原创,输出有价值的文章!

同学,如果文章有帮助到你,请通过以下方式给笔者反馈:

最近笔者在整理第一本电子书书稿《前端面试手册》,有兴趣的同学可以点个✨star✨关注下