我们可以很容易地在 CSS 中创建变量:
:root {
--scale: 1;
}
我们可以在任何元素上声明它们:
.thing {
transform: scale(--scale);
}
像这样的例子更好的是在用户交互上应用变量,比如说 :hover
:
:root {
--scale: 1;
}
.thing {
height: 100px;
transform: scale(--scale);
width: 100px;
}
.thing:hover {
--scale: 3;
}
但是,如果我们想在动画中使用该变量……nada。
: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;
}
现在我们得到动画!
你会想要 检查浏览器支持 自 @property
仅登陆 Chrome (开始于 85版) 在撰写本文时。 如果你希望用它嗅出它 @supports
,我们目前不走运,因为它不接受 at-rules 作为值……但是。 这将改变一次 at-rule()
变成真实的东西.