CSS自定义属性(CSS变量)

除了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')
  }

img

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值