除了sass,less等预编译器外,css自身也支持定义变量
html
<section>
<i></i>
<div>
test test test test test test test test test test test test test test test test test test test test test
</div>
</section>
<div id="test">
<div id="test__title">font-size:28px</div>
</div>
css
/*全局变量*/
:root {
--bgcolor: yellow;
--sec-color:blue;
--font-size:22px;
--quanjv:1;
/*[JS] getComputedStyle(document.body).getPropertyValue('--quanjv')//'1' */
}
section {
background: var(--bgcolor);/*取--bgcolor的值*/
color:var(--sec-color,blue);/*取--sec-color的值,如果没有,则使用默认值(blue)*/
--multy:20;
width: calc(var(--font-size) * var(--multy)*1.1);/*多个变量计算*/
}
section:after{
content: '';
display: block;
clear: both;
}
section i {
width: 100px;
height: 100px;
background: currentColor;/*使用默认颜色,取color的值,没定义取父元素的color*/
display: inline-block;
float: left;
border-radius: 50%;
shape-outside: circle();
margin: 10px;
}
/*局部变量*/
section div {
word-break: break-all;
font-size:var(--font-size,14px);/*找不到该变量,不在变量的作用域,使用默认值14px*/
}
#test__title{
font-size:var(--font-size,10px);/*使用局部变量,在下方*/
}
#test{
--font-size:28px;/*定义局部变量*/
--jubu:2;
/*[JS] getComputedStyle(document.body).getPropertyValue('--quanjv') = '' ,无法获取;
getComputedStyle(document.getElementById('test')).getPropertyValue('--jubu') = "2"
*/
}
@supports(--a:0){
/*支持*/
}
@supports(not(--a:0)){
/*不支持*/
}
还可以JS操作
//改变变量
document.documentElement.style.setProperty('--sec-color','red');//JS操作
//获得变量
getComputedStyle(document.body).getPropertyValue('--quanjv');//1
//获取支持性
if(window.CSS&&window.CSS.supports&&window.CSS.supports('--a',0)){
console.log('support')
}else{
console.error('not support')
}