不要错过 CSS 变量
最初听说CSS 变量时,我有点怀疑。既然已经有像 scss、sass、less 和 stylus 这样的扩展语言了,为什么还会有人用它呢?几年后,我开始注意到越来越多的人在使用它、撰写文章、讨论它。我好像错过了什么……虽然花了一段时间,但在反复使用之后,我渐渐迷上了它。在这篇文章中,我将讲述是什么促使我进一步探索 CSS 变量,并开始在项目中使用它们。
用法
要声明变量,请在选择器中定义它们,并在变量名称前加上两个破折号 ( --
):
div {
--bgColor: deeppink;
}
一种流行的方法是使用选择器定义变量:root
,这样就可以定义全局变量:
:root {
--bgColor: teal;
}
要使用变量,请使用以下var()
函数:
div {
background: var(--bgColor);
}
该var()
函数接受第二个参数,如果变量尚未声明,则该参数用作后备:
header {
background: var(--bgColor);
color: var(--color, beige);
}
上述代码片段的结果是:
主题
使用 css 变量,创建主题变得简单。
根据body
的类,我们可以将变量设置为适当的值:
body.sunrise {
--background-color: #fff;
--text-color: #333;
}
body.sunset {
--background-color: #333;
--text-color: #fff;
}
然后我们可以在设置元素样式时使用这些变量:
html,
body {
background: var(--background-color);
color: var(--text-color);
}
如果body
的 class 更改为sunrise
或sunset
,则 css 变量将级联到所有选择器。
在本例中,我们将过渡到浅色或深色主题:
JavaScript API
在我看来,这是最好的部分。CSS 变量有一个 JavaScript API 来获取和设置变量。
要获取变量,请使用该getPropertyValue
方法:
getComputedStyle(document.documentElement).getPropertyValue('--color')
要从元素中获取值,首先使用以下方法选择该元素querySelector
:
getComputedStyle(document.querySelector('h1')).getPropertyValue('--color')
要设置变量值,请使用style.setProperty
:
document.documentElement.style.setProperty('--color', 'red')
要设置元素的值:
document.querySelector('h1').style.setProperty('--color', 'blue')
此 API 提供了一些以干净的方式使用 css 变量的机会。
几天前,我在David K.的一个XState演示(https://codepen.io/davidkpiano/pen/zWrRye )中遇到了这个用例。他使用 CSS 变量在用户在屏幕上拖动鼠标时创建一个选择框。
选择框的 css 使用变量来知道框的四个角(基于起点和鼠标的当前位置):
.selectbox {
left: calc(var(--mouse-x1));
top: calc(var(--mouse-y1));
width: calc((var(--mouse-x2) - var(--mouse-x1)));
height: calc((var(--mouse-y2) - var(--mouse-y1)));
color: rgba(255, 255, 255, 0.5);
background: rgba(0, 0, 0, 0.1);
border: 2px solid currentColor;
position: absolute;
transition: opacity 0.3s ease-in-out;
}
监听鼠标事件,并相应地更新鼠标点:
document.documentElement.style.setProperty(
'--mouse-x1',
ctx.selectArea.x1 + 'px',
)
document.documentElement.style.setProperty(
'--mouse-y1',
ctx.selectArea.y1 + 'px',
)
document.documentElement.style.setProperty(
'--mouse-x2',
ctx.selectArea.x2 + 'px',
)
document.documentElement.style.setProperty(
'--mouse-y2',
ctx.selectArea.y2 + 'px',
)
结束语
如果你和我一样,没有意识到 CSS 变量的用处,或者根本不知道它们的存在,
我希望这篇文章能为你打开探索其用例的大门。
我偶然发现了 JavaScript API,但这个 API 让我了解了它们在现实世界中的用法,我期待着将来能更多地使用和体验它们。