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

如何实现CSS从纯色背景到渐变背景的平滑过渡?

简洁实现纯色到渐变背景的过渡效果

这里有两种更简洁的方案,不用写重复的自定义属性:

方案1:伪元素叠加法(推荐,兼容性好)

利用伪元素承载渐变背景,默认隐藏,hover时显示,通过过渡opacity实现平滑切换:

.tile {
  background-color: #e6e6e6;
  position: relative;
  /* 基础样式:设置宽高、padding等 */
}

.tile::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1; /* 确保内容在渐变上方 */
}

.tile:hover::before {
  opacity: 1;
}

原理:初始状态下,元素显示自身的纯色背景;hover时,伪元素的渐变背景逐渐显现,视觉上就是纯色到渐变的平滑过渡。

方案2:单自定义属性简化法

只定义一个自定义属性控制渐变的其中一个颜色,初始时让渐变的两个颜色一致(模拟纯色),hover时修改该属性实现过渡:

@property --grad-start {
  syntax: "<color>";
  initial-value: #e6e6e6;
  inherits: false;
}

.tile {
  background: linear-gradient(var(--grad-start), #e6e6e6);
  transition: --grad-start 0.3s ease;
  /* 基础样式 */
}

.tile:hover {
  --grad-start: #667eea;
  background: linear-gradient(var(--grad-start), #764ba2);
}

这种方法只用一个自定义属性,避免了冗余代码,不过需要浏览器支持@property(现代浏览器基本都支持)。

内容的提问来源于stack exchange,提问作者Hashim Aziz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:52:38