css变量的声明和读取
1、css变量的声明
使用--声明变量($被sass用掉了,@被less用掉了)
<style>
:root {
--color: red;
}
</style>
root为根元素,相当于给html设置了css变量
/* :root 相当于 html */
html {
--color: red;
}
2、变量的读取
通过val函数读取
div {
color: var(--color);
}

val函数第二个参数,可选值,当变量不存在时读取第二个值

3、变量的类型
①当变量的类型为字符串时,可以与其他字符串拼接
div::after {
--text1: 'hello ';
--text2: var(--text1) 'world';
content: var(--text2, '萨瓦迪卡') '!'
}

②当变量的类型为数字时,不能和单位直接拼接,需要用calc函数拼接
div {
color: var(--color, blue);
--width: 50;
width: calc(var(--width) * 1px);
background-color: red;
}

4、变量的作用域
变量的作用域就是它所在选择器的范围
当作用域内有多个同名变量,按优先级最高的生效,同样式生效的规则一致

全局的变量通常放在根元素:root里面,这样任何选择器都可以读取
5、响应式布局
<style>
body {
--primary: blue;
--secondary: blue;
}
a {
color: var(--primary);
text-decoration-color: var(--secondary);
}
@media screen and (min-width: 350px) {
body {
--primary: red;
--secondary: red;
}
}
</style>
</head>
<body>
<a href="">链接1</a>
<a href="">链接2</a>
</body>


6、兼容性处理
div{
color: red;
color: val(--color);
}
7、内联重新赋值css变量
通过getComputedStyle(document.documentElement).getPropertyValue('--c-999')可以获取到html标签中定义的--c-999变量
①此时div的颜色为#999

②style属性中可以重新定义--c-999的颜色

8、js操作
①通过setProperty设置css变量

②通过removeProperty删除css变量

③写一段在css中无用但在js中可以读取的代码
<style>
:root {
--foo: if(x > 5) this.width = 10;
}
</style>
</head>
<body>
<script>
const res = getComputedStyle(document.documentElement).getPropertyValue('--foo')
console.log(res.trim()) // if(x > 5) this.width = 10
</script>
</body>


浙公网安备 33010602011771号