css变量

时间:2022-10-06 21:50:38

CSS变量:

目前主流浏览器都已支持CSS变量,Edge 浏览器也支持 CSS 变量。用户可以方便地在css中使用自定义变量。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body> <style>
/*css变量*/
/*兼容性检测*/
@supports ((--a:0)){
/*css变量的作用域为所在的选择器上,:root上声明的css变量具有全局作用域*/
:root{
--bgcolor:#fff;
--color:green;
--fsize:18px;
--size:20; }
.first-p{
/*--bgcolor的作用域为first-p选择符所在的元素*/
--bgcolor:yellow;
background-color:var(--bgcolor);
font-size:var(--fsize);
color:var(--color);
}
.second-p{
font-size:calc(var(--size)*1px); /*数值和字符串拼接时,使用calc()*/
}
}
@supports (not(--a:0)){
.first-p{
background-color:#ff55ff;
font-size:12px;
color:red
}
</style> <div>
<p class="first-p">this is first paragraph.</p>
<p class="second-p">this is first paragraph.</p>
<p class="third-p">this is first paragraph.</p>
</div> <script>
//js检测css变量的兼容性
var isSupported = window.CSS && window.CSS.supports && window.CSS.supports('--a', 0); </script>
</body>
</html>