高级前端
css
【Q184】有没有使用过 css variable,它解决了哪些问题

有没有使用过 css variable,它解决了哪些问题

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 185 (opens in a new tab)

Author 回答者: Cicelychen (opens in a new tab)

css变量减少样式重复定义,比如同一个颜色值要在多个地方重复使用,以前通过less和sass预处理做到,现在css变量也可以做到,方便维护,提高可读性

:root{
  --bgcolor: blue;
  --color: red;
}
p {
  color: var(--color);
}
div {
  backgroung-color: var(--bgcolor);
  color: var(--color)
}

在媒体查询中使用,精简代码,减少冗余

.box {
  --base-size: 10;
  width: calc(var(--base-size)* 10px);
  height: clac(var(--base-size)* 5px);
  padding:calc(var(--base-size) * 1px);
}
@media screen and (min-width: 1480px) {
  .box{
    --base-size: 8;
  }
}

方便在js中使用

// 设置变量
document.getElementById("box").style.setPropertyValue('--color', 'pink')
// 读取变量
doucment.getElementById('box').style.getPropertyValue('--color').trim()    //pink
// 删除变量
document.getElementById('box').style.removeProperty('--color')

Author 回答者: shfshanyue (opens in a new tab)

可在运行时控制 CSS 逻辑,与 less/sass 相比,更加灵活,因为它很容易通过 JS 来控制。

补充两个用途:

  1. 可以减少 JavaScript 对 DOM 的介入,制作性能更高的动画
  2. 配合 content 等通过 CSS 给 JS 传参,得到一些通过 JavaScript 难以获取的参数

https://www.zhangxinxu.com/wordpress/tag/css-var/ (opens in a new tab)

Author 回答者: liusshuai (opens in a new tab)

对浏览器兼容性有要求吗

Author 回答者: linlai163 (opens in a new tab)

对浏览器兼容性有要求吗

现在主流浏览器都支持了,可以 MDN 或者 Can I use 里面自己查一下

Author 回答者: zhengaimin (opens in a new tab)

css变量减少样式重复定义,比如同一个颜色值要在多个地方重复使用,以前通过less和sass预处理做到,现在css变量也可以做到,方便维护,提高可读性

:root{
  --bgcolor: blue;
  --color: red;
}
p {
  color: var(--color);
}
div {
  backgroung-color: var(--bgcolor);
  color: var(--color)
}

在媒体查询中使用,精简代码,减少冗余

.box {
  --base-size: 10;
  width: calc(var(--base-size)* 10px);
  height: clac(var(--base-size)* 5px);
  padding:calc(var(--base-size) * 1px);
}
@media screen and (min-width: 1480px) {
  .box{
    --base-size: 8;
  }
}

方便在js中使用

// 设置变量
document.getElementById("box").style.setPropertyValue('--color', 'pink')
// 读取变量
doucment.getElementById('box').style.getPropertyValue('--color').trim()    //pink
// 删除变量
document.getElementById('box').style.removeProperty('--color')

document.getElementById("box").style.setPropertyValue('--color', 'pink') 这句 setPropertyValue 是不是写错了,我在 MDN 上只看到了 setProperty 这个 API https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration/setProperty (opens in a new tab)

Author 回答者: Jupiter-u (opens in a new tab)

document.getElementById("box").style.setPropertyValue('--color', 'pink') // 读取变量 doucment.getElementById('box').style.getPropertyValue('--color').trim() //pink

set的时候不加Value get的时候加Value。。。。。(●'◡'●)

正确写法: document.getElementById("box").style.setProperty('--color', 'pink') // 读取变量 doucment.getElementById('box').style.getPropertyValue('--color').trim() //pink // 删除变量 document.getElementById('box').style.removeProperty('--color')

Author 回答者: shfshanyue (opens in a new tab)

@Jupiter-u 确实如此,这种用法实在是太难记了。

哦对,你的回答中的代码可以通过 ``` 包裹,可以使其语法高亮。