前端有时候会接到文字颜色渐变,同时有文字阴影的需求,如下图
一般会想到如下实现方法
// 实现文字颜色渐变
background-image: linear-gradient(360deg, #f6130c 0%, #f87052 100%);
-webkit-background-clip: text;
webkit-text-fill-color: transparent;
// 实现文字阴影
text-shadow: 0 4rpx 0 #bc6d05;
理想很丰满,现实很骨感,上面代码的实际效果是这样的
text-shadow覆盖了文字颜色渐变的样式。网上搜索后整理了解决方案如下。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<style type="text/css">
div {
text-align: center;
font-size: 80px;
position: relative;
color: #f6130c;
// 设置文字阴影
text-shadow: 0 4px 0 #bc6d05;
font-weight: bold;
}
div::before {
content: attr(text);
position: absolute;
z-index: 10;
color: #f6130c;
// 渐变样式
background-image: linear-gradient(360deg, #f6130c 0%, #f87052 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
// 去除继承父级样式
text-shadow: none;
}
</style>
</style>
</head>
<body>
<div text="ICU">ICU</div>
原理:在原来的文字上,通过绝对定位覆盖多一层,底层用text-shadow ,上层文字相同,设置渐变样式。
注意:如果你是在开发微信小程序,上面代码中的attr属性不支持,所以没办法使用::before + content: attr(text)这种方式去复制相同的文字,不过原理懂了,我想你应该知道怎么绕过这个问题了。
参考