You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS如何实现linear-gradient线性渐变背景占比的平滑过渡动画

CSS 原生不支持直接对 linear-gradient 的色标位置做插值过渡,所以你直接在动画起止关键帧写不同色标的渐变,只会出现跳变效果,不会平滑过渡。

方案1:现代浏览器最优方案(通过@property注册可动画自定义变量)

这个方案可以直接实现渐变占比的平滑变更,不需要调整原有渐变的逻辑,鼠标移入移出都能自动触发过渡:

/* 注册可动画的百分比类型自定义属性 */
@property --gray-end {
  syntax: '<percentage>';
  inherits: false;
  initial-value: 70%;
}
@property --blue-end {
  syntax: '<percentage>';
  inherits: false;
  initial-value: 85%;
}

div {
  width: 200px;
  height: 50px;
  /* 用变量定义渐变的色标位置 */
  background: linear-gradient(135deg, gray 0%, gray var(--gray-end), blue var(--gray-end), blue var(--blue-end), red var(--blue-end));
  /* 给两个变量加过渡效果 */
  transition: --gray-end 0.5s ease, --blue-end 0.5s ease;
}

div:hover {
  /* hover时直接修改变量值即可触发平滑过渡 */
  --gray-end: 50%;
  --blue-end: 75%;
}
<div></div>

该方案兼容 Chrome 85+、Edge 85+、Safari 16.4+,覆盖 90% 以上的全球活跃用户。

方案2:低版本浏览器兼容方案(通过background-position模拟)

如果需要兼容更旧的浏览器,可以用你提到的背景位移方案实现视觉等效效果:

div {
  width: 200px;
  height: 50px;
  /* 将两种状态的渐变提前整合到同一张渐变图中 */
  background: linear-gradient(135deg, gray 0%, gray 35%, blue 35%, blue 42.5%, red 42.5%, red 50%, gray 50%, gray 75%, blue 75%, blue 92.5%, red 92.5%);
  background-size: 200% 100%;
  background-position: left top;
  transition: background-position 0.5s ease;
}

div:hover {
  background-position: right top;
}
<div></div>

这个方案通过移动背景位置切换渐变显示区域,所有支持CSS过渡的浏览器都能兼容。

内容的提问来源于stack exchange,提问作者Ronny Efronny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:36:03