css - :root pseudo class 的用途

标签 css

我刚刚找到了 :root 伪类。

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

https://developer.mozilla.org/en-US/docs/Web/CSS/:root

它到底有什么用?当您可以只使用 html 选择器时,为什么除了更高的特异性之外还有人会使用它?

最佳答案

这里的答案是:

except that its specificity is higher.

为什么重要?

在正常的 CSS 场景中,如果你有这样的东西:

html {
    background-color: red;
}

html {
    background-color: blue;
}

您将获得蓝色背景,因为它是最后计算的。可以看到here .

但是,如果你有这个:

:root {
    background-color: red;
}

html {
    background-color: blue;
}

您将获得红色背景。可以看到here .

想象这样一种场景,您导入了多个库,然后其中一些库在您想要删除的 html 上设置了一些属性。您可以将您的属性定义为 !important,您可以组织您的导入以便最后评估您想要的内容,或者您​​可以使用 :root 选择器。


其他场景

正如@user2864740 和@13ruce1337 所指出的,CSS 不仅适用于HTML,还可以适用于any kind of XML document, including plain XML, SVG and XUL。 . :root 伪类将正确选择其他类型文档的根。

关于css - :root pseudo class 的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23551633/

相关文章:

html - Bootstrap 4 中旋转木马图像顶部意外的白色背景

javascript - 从 ASPX 后面的代码中显示/隐藏 div

javascript - 如何使用 addclass 和 removeclass 方法更改 textarea(NicEdit 中使用的 textarea)的 css 类

html - jQuery Mobile 输入宽度

javascript - 我使用 css zIndex 的简单 jquery 幻灯片无法正常工作

javascript - jQuery:将鼠标悬停在子菜单项上时保持子菜单打开

html - 如何制作响应式两个内联 block div

jquery - 删除 facebook likebox 滚动条

html - 字体未正确呈现

jquery - 溢出:隐藏属性在 Firefox 中表现异常/在 Chrome/Safari 中表现良好