CSS :root
CSS中的此伪类与文档的根元素匹配。它选择文档树或DOM中最高级的父级。
在HTML中,
<html> 元素始终是根元素。尽管
:root 等同于
html 选择器,因为它们都针对同一元素,但是
:root 选择器具有更高的特异性。
语法
:root {
// CSS property
}
示例
<!DOCTYPE html>
<html>
<head>
<title>:root selector</title>
<style>
:root {
background: lightblue;
color: blue;
text-align: center;
}
</style>
</head>
<body>
<h1>欢迎来到lidihuo.com</h1>
<h2>这是:root选择器的示例</h2>
</body>
</html>
输出:
现在,让我们同时尝试
html 选择器和
:root 选择器。尽管它们的工作原理相似,但在特异性方面,
:root 选择器获胜。
示例
在此示例中,我们将在
html 选择器和
:root 选择器中定义相同的属性。由于具有更高的特异性,
:root 选择器中的属性将起作用。但是那些不在
:root 选择器中但在
html 选择器中提到的属性,则
html 选择器的属性将起作用。
示例
<!DOCTYPE html>
<html>
<head>
<title>:root selector</title>
<style>
:root {
background-color: lightblue;
color: blue;
text-align: center;
}
html {
background-color: red;
color: white;
font-size: 30px;
}
</style>
</head>
<body>
<h1>欢迎来到lidihuo.com</h1>
<h2>这是:root选择器和html选择器的示例</h2>
</body>
</html>
输出:
在上面的示例中,我们可以看到
html 和
background-color 和
color 属性
:root 选择器,但在输出中,
:root 选择器中提到的属性将起作用。这是因为
:root 选择器的特异性更高。