继承
自上而下继承,父类无法获取子类中定义的变量
定义方式(--开头,大小写敏感)
CSS定义
body {
--theme: #000000
}
JS定义
<script>
document.body.style.setProperty('--theme', '#000000')
</script>
使用方式(变量定义完成后只能作为属性值使用)
.container {
color: var(--theme, #00FF00); // 第二个参数为未设置变量时的默认值
}
JS获取设置的值
属性获取
document.styleSheets[0].cssRules[0].style.getPropertyValue('--theme')
内联样式获取
document.body.style.getPropertyValue('--theme')
用途
全局统一配色方案设置(全局换肤)
// index.html
style>
body {
background-color: var(--theme);
}
</style>
// index.html
<script>
document.body.style.setProperty('--theme', '#000000')
</script>
动态拼接
数值
body {
--number: 60;
font-size: calc(var(--number) * 1px);
}
字符串
body:after {
--string: 'hello';
content: var(--string)'word!';
color: #FF0000;
}
响应式动态设置
body {
background-color: var(--theme);
font-size: calc(var(--number, 60) * 1px);
}
@media screen and (min-width: 600px) and (max-width: 800px) {
body {
--number: 30px
}
}