其他分享
首页 > 其他分享> > css实现文字渐变色(兼容性写法、渐进增强、平稳退化)

css实现文字渐变色(兼容性写法、渐进增强、平稳退化)

作者:互联网

一、第一种方法通过background-clip实现

原理:为文字设置渐变背景颜色,并设置透明颜色字体,使用background-clip:text对背景进行裁剪,留下文本部分的背景,从而实现渐变效果。

问题:background-clip: text的兼容性并不好,一旦浏览器不兼容,背景就会直接暴露出来。

<span class="linear-gradient-text"></span>
.linear-gradient-text {
  background: linear-gradient(to right, red, blue);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

浏览器支持background-size:text情况下:
在这里插入图片描述
浏览器不兼容情况下:
在这里插入图片描述

解决办法:如果对兼容性要求不高,且为了保证平稳退化,可以使用css的特征检测选择器@supports,虽然这个选择器本身也有兼容性问题,但是这样写至少能保证有一个默认颜色。

可以到https://caniuse.com/,查看具体的浏览器支持度。

.linear-gradient-text {
    color: blue;
	@supports (-webkit-background-clip: text) or (background-clip: text) {
		background: linear-gradient(to right, red, blue);
		-webkit-background-clip: text;
		background-clip: text;
		color: transparent;
    }
}

浏览器不兼容情况下:
在这里插入图片描述

二、第二种方法通过svg标签实现(只要浏览器支持svg标签就行,兼容性相比第一种要好)

<!--x1,y1,x2,y2控制渐变方向-->
<svg>
   <defs>
      <linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="0%">
      	<stop offset="0%" style="stop-color:red; stop-opacity:1" />
      	<stop offset="100%" style="stop-color:blue; stop-opacity:1" />
      </linearGradient>
   </defs>
   <text x="0" y="36" fill="url(#grad)" style="font-size:36px">渐变文字</text>
</svg>

标签:兼容性,浏览器,linear,clip,gradient,渐变色,background,text,css
来源: https://blog.csdn.net/java_wzh123/article/details/120171391