主题
CSS 变量
提示
IE: 啊这?
定义 CSS 变量
css
:root {
--width: 100px;
}
.box {
--height: 100px;
}使用 CSS 变量
css
.box {
width: var(--width);
height: var(--height, 100px); /* 未定义时使用后备值 */
}自定义属性会继承;定义在 :root 上时,通常可作为全局设计令牌使用。定义在组件选择器上时,只在该元素及其后代中生效。
通过 JS 来使用 CSS 变量
获取变量
js
getComputedStyle(document.querySelector(':root')).getPropertyValue('--width')
getComputedStyle(document.querySelector('.box')).getPropertyValue('--height')设置变量值
js
document.querySelector(':root').style.setProperty('--width', '50px')
document.querySelector('.box').style.setProperty('--height', '50px')