我们终于可以实现 CSS 渐变动画了

2025-06-04

我们终于可以实现 CSS 渐变动画了

在css-tip.com上了解更多 CSS 技巧

得益于CSS 属性和值 API 级别 1@property规范中的新定义,我们现在可以使用自定义属性(又名 CSS 变量)进行转换。

@property --my-var {
  syntax: '<integer>';
  inherits: false;
  initial-value: 0;
}
Enter fullscreen mode Exit fullscreen mode

所有的技巧都在syntax允许我们明确定义属性类型的部分中,因此浏览器将知道如何在值之间进行插值(我们想要的转换)

指定@property规则所表示的自定义属性注册的语法,控制在计算值时如何解析属性的值。

考虑到这一点,我们只需要使用渐变定义中的变量并为其设置动画。

动画颜色

我们使用<color>语法

动画颜色大小

我们可以使用<percentage><length>或者<angle>根据每个用例

动画方向

我们使用<angle>

动画位置

我们使用<percentage><length>


如您所见,这很简单,并且在所有情况下代码都如下所示:

/* we define the variable */
@property --a{
  syntax: '<percentage>'; /* its type */
  inherits: false;
  initial-value: 10%; /* the initial value */
}
/**/
.box {
  transition:--a 0.5s; /* we add transition to it */
  background:linear-gradient(red var(--a),blue); /* we use it inside the gradient */
}
.box:hover {
  --a:50%; /* we update on hover */
}
Enter fullscreen mode Exit fullscreen mode

我们可以有复杂的动画:

并使用keyframes


给我买杯咖啡

或者

成为赞助人

文章来源:https://dev.to/afif/we-can-finally-animate-css-gradient-kdk
PREV
托管应用程序的 5 种方法
NEXT
升级 CSS 多行打字机效果