1、定义变量 --
- 以
--
开头,大小写敏感
- 变量的定义必须有作用域,不能在外部直接定义,这点与scss和less不同
:root[theme="blue"] {
--btnColor: blue;
--btnBg: #ddd;
}
2、使用变量 var(variable_name, def_value)
- var的第一个参数为变量名,第二个参数为变量找不到时的默认值
.test {
--w: 50px;
width: var(--w);
}
.test::after {
/* 字符串拼接 */
--c: '*name:';
content: var(--c)'wxm';
}
.test {
/* 数值计算 */
--w: 50;
height: calc(var(--w) * 2px);
}
3、变量 currentColor
- currentColor会取当前元素的color属性值
- 使用场景之一:svg图标的颜色设置为currentColor,以父元素的color来控制图标的颜色
4、获取css变量值 style.getPropertyValue
document.body.style.getPropertyValue('--color')
5、修改css变量值 style.setProperty
document.body.style.setProperty('--color', 'red');
6、应用
@media screen and (min-width: 600px) {
body {
--card-width: 100px;
}
}
@media screen and (min-width: 760px) {
body {
--card-width: 200px;
}
}
:root[theme="blue"] {
--btnColor: blue;
--btnBg: #ddd;
}
:root[theme="dark"] {
--btnColor: #000;
--btnBg: #fff;
}