字体同时设置阴影➕渐变的两种方法

156 阅读1分钟

1️⃣ 伪元素 2️⃣ 元素叠加

  1. 伪元素(通用,容易出现偏移的情况)
<div className="main-title"  id="dynamic-main-title"> {this.state.mainTitle} </div>

![问题.png](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6af6c69c8ad94b4c804b8c41fa5f07ac~tplv-k3u1fbpfcp-jj-mark:0:0:0:0:q75.image#?w=358&h=140&s=35519&e=png&b=f55932)
![问题.png](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c0b469ff2ee440a4b91de0c6ffc259bd~tplv-k3u1fbpfcp-jj-mark:0:0:0:0:q75.image#?w=358&h=140&s=35519&e=png&b=f55932)
.main-title {  
  background: linear-gradient(to top, #fef7dd, #fffdfa);  
  background-clip: text; // 背景剪裁  
  color: transparent; //背景设置为透明  
  position: relative;  
}  
/* 伪元素设置阴影 */  
.main-title::before {  
  content: attr(data-title);  
  position: absolute;  
  z-index: -1;  
  text-shadow: 0 0.04rem 0.0533rem rgba(0, 0, 0, 0.25);  
}

getMainTitleContent() {  
  const dynamicTitle = document.getElementById('dynamic-main-title')  
  const titleText = this.state.mainTitle  
  dynamicTitle.setAttribute('data-title', titleText)  
}

  1. 元素叠加(适用于字体本身已绝对定位!比较好用)
<div className="title" > 公告 </div>  
<div className="title_shadow"> 公告 </div>

.title {  
  background: linear-gradient(to top, #fef7dd, #fffdfa);  
  background-clip: text;  
  color: transparent;  
  position: absolute;   
  left: 50%;  
  transform: translate(-50%, -50%);  
}  
/* 叠加设置阴影 */  
.title_shadow {  
  color: transparent;  
  text-shadow: 0 0.04rem 0.0533rem rgba(0, 0, 0, 0.25);  
  position: absolute;  
  left: 50%;  
  transform: translate(-50%, -50%);  
  z-index: -1;  
}

注意: 若包裹字体的 div 只有字体大小,没有宽高,在某些机型上(iphone x)会出现意外的线条,因为 background-clip: text; 没有剪切好。此时需要设置一下高度。

问题.png