CSS 有两种方法可以定位 HTML 文档的根元素——:root
伪类和html
选择器。虽然它们彼此非常相似,但您应该知道它们有一些不同之处。
选择器特异性
选择器:root
比选择器具有更高的特异性html
。这是因为:root
是一个伪类选择器,而html
是一个类型选择器。
:root {
background-color: red;
}
html {
background-color: blue;
}
/* The HTML document's root element will have a red background-color. */
定位根元素
除了 HTML,CSS 还可用于设置其他类型文档的样式。这是:root
元素发挥作用的地方,允许您为文档的根元素设置样式。This can be especially important when styling SVG documents, where the html
selector will not work.