1. 使用 background-clip 实现文字渐变
background-image: linear-gradient(to bottom, #ec428c, #32d1d3); // 背景线性渐变
color: #ffffff; // 兜底颜色,防止文字裁剪不生效
background-clip: text;
-webkit-background-clip: text; // 背景被裁减为文字的前景色
-webkit-text-fill-color: transparent; // 文字填充为透明,优先级比color高。
可能会出现的问题:
踩坑 1: 线性渐变字体消失
在低端 ios 机型上,出现过线性渐变字体消失的问题,排查发现是因为background-clip 无法 display: flex布局下生效。所以开发过程中务必做好兜底,防止这两种样式出现在同一个 dom 上。
踩坑 2: 线性渐变字体在部分 ios 机型上出现一条线
使用这种方式实现线性渐变,在部分 ios 机型上会出现奇怪的线,可以将背景设置为no-repeat,并适当缩小。
background-repeat: no-repeat;
background-size: 98% 98%;
background-position: 50% 50%;
2. 使用 -webkit-mask 实现文字渐变
<div class="word" data-text="文字渐变">文字渐变</div>
.word {
position: relative;
color: #ec428c;
&:after {
content: attr(data-text);
position: absolute;
top: 0;
left: 0;
z-index: 10;
color: #32d1d3;
-webkit-mask: linear-gradient(to bottom, transparent, green);
white-space: nowrap;
}
}