今天发现一个 CSS 写法,之前一直以为文字渐变要用 Canvas 或者图片,结果纯 CSS 就能搞定。
效果
文字从一种颜色平滑过渡到另一种颜色。很多网站的标题都用这种效果。
实现
.gradient-text {
background: linear-gradient(90deg, #667eea, #764ba2, #f093fb);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
color: transparent; /* 兜底 */
}
原理:把渐变背景裁剪到文字形状上,然后把文字本身的颜色设为透明——露出来的就是背景渐变色。
加上动画
.gradient-text-animated {
background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #667eea);
background-size: 200% auto;
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
animation: gradient-shift 3s linear infinite;
}
@keyframes gradient-shift {
to {
background-position: 200% center;
}
}
渐变背景在文字上流动,效果很炫。
兼容性
background-clip: text 在 2026 年全球支持率 97%+,放心用。-webkit-background-clip 是为了兼容旧版 Safari。
其他玩法
/* 文字 + 图片背景 */
.image-text {
background: url('/texture.jpg') center / cover;
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
/* 配合 filter 做发光效果 */
.glow-text {
background: linear-gradient(90deg, #00f2fe, #4facfe);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
filter: drop-shadow(0 0 8px rgba(79, 172, 254, 0.5));
}
一个小技巧,分享出来。