我们可以很容易地在CSS中制作变量
:root {
--scale: 1;
}
而且我们可以在任何元素上声明它们
.thing {
transform: scale(--scale);
}
对于这样一个例子来说,更好的做法是将变量应用于用户交互,比如说:hover:
:root {
--scale: 1;
}
.thing {
height: 100px;
transform: scale(--scale);
width: 100px;
}
.thing:hover {
--scale: 3;
}
CodePen嵌入回退
但如果我们想在一个动画中使用这个变量......没有:
:root {
--scale: 1;
}
@keyframes scale {
from { --scale: 0; }
to { --scale: 3; }
}
/* Nope! */
.thing {
animation: scale .25s ease-in;
height: 100px;
width: 100px;
}
这是因为该变量被识别为一个字符串,而我们需要的是一个可以在两个数字值之间插值的数字。这就是我们可以调用@property ,不仅将变量注册为一个自定义属性,而且将其语法定义为一个数字。
@property --scale {
syntax: "<number>";
initial-value: 1;
inherits: true;
}
现在我们得到了动画!
CodePen嵌入回退
你要检查浏览器的支持情况,因为截至目前,@property 只登陆了Chrome(从85版本开始)。如果你要使用它,最好在它被支持的地方使用它。看起来我们可以使用@property 中的属性,通过@supports 来探测。
@supports (inherits: true) {
/* Styles for supporting browsers. */
}