Skip to main content

如何实现文本渐变

简介#

渐变 image.png

background: linear-gradient(0deg, red, blue);
background: linear-gradient(90deg, red, blue);
background: linear-gradient(180deg, red, blue);

1. css实现文本渐变#

单行渐变#

image.png 竖向渐变, display 必须是纯inline

display: inline;
background-image: linear-gradient(0deg,#67cff3,#fff);
-webkit-background-clip: text;
color: transparent;

意义:相比单色更加清晰

原理解释:

  • background-image: linear-gradient(0deg,#67cff3,#fff); 为文本提供渐变背景
  • -webkit-text-fill-color: transparent 或者  color: transparent;  透明色填充文本
  • -webkit-background-clip: text; 文本剪辑背景填充文本

注意: -webkit-background-clip 必须位于 background-image 之后

整体渐变#

image.png

display: 非inline 即可

2. svg实现文本渐变#

image.png

<div class="box svg_box">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
width="500" height="300" viewBox=""viewBoxs="0 0 500 300">
<defs>
<linearGradient id="g1" gradientUnits="userSpaceOnUse" x1="0" y1="10" x2="0" y2="50">
<stop offset="0" style="stop-color: blue"/>
<stop offset="0.7" style="stop-color: red"/>
</linearGradient>
</defs>
<text x="0" y="30" fill="url(#g1)">
新华社北京9月21日电 国家主席习近平21日在联合国成立75周年纪念峰会上发表重要讲话。
</text>
</svg>
</div>

缺点:

  • 文本换行需要手动借助标签
  • 渐变路径需要中自定义, 且id必须唯一

3. webkit 内核浏览器特有 -webkit-mask-image: -webkit-gradient()#

参考: 单行渐变:https://chaolucky.com/blog/05/25-98.html

SVG text文本换行和foreignObject换行对比 : [https://www.zhangxinxu.com/study/201708/svg-text-vs-svg-foreignobject.html](