CSS变量及其使用

继承

自上而下继承,父类无法获取子类中定义的变量

定义方式(--开头,大小写敏感)

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
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值