gpt4 book ai didi

css - :root pseudo class 的用途

转载 作者:行者123 更新时间:2023-11-28 08:36:48 25 4
gpt4 key购买 nike

我刚刚找到了 :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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com