一、 text-stroke属性
原理 :将文字颜色设为透明,给文字添加描边,只保留描边部分,形成镂空效果。
.text {
color: transparent;
-webkit-text-stroke: 2px #3498db; /* 描边宽度和颜色 */
text-stroke: 2px #3498db;
}
备注: 支持渐变描边:text-stroke: 2px linear-gradient(…)
进阶: 动态渐变背景(文字区域会透出背景渐变)
<div class="box">
<h1class="title">夏日特惠</h1>
</div>
.box{
background: linear-gradient(45deg, #ff9a9e, #fad0c4);
padding: 3rem;
}
.title {
font-size: 5rem;
color: transparent;
-webkit-text-stroke: 3px #fff;
text-stroke: 3px #fff;
}
二、兼容方案:伪元素叠加法
原理:使用两层文字叠加,底层为描边文字,顶层为小一号的实心文字,通过错位形成镂空边缘。
.text {
position: relative;
font-size: 4rem;
font-weight: bold;
color: #2980b9; /* 描边色 */
}
/* 创建镂空层 */
.text ::after {
content: attr(data-text); /* 复用元素文字 */
position: absolute;
top: 3px; /* 微调位置 */
left: 3px;
color: white; /* 背景色 */
font-size: 0.92em; /* 小于原文字 */
}
优点:
1、兼容所有浏览器(包括IE9+)
2、可通过调整top/left值和字体大小控制镂空厚度
3、支持复杂背景(图片、视频背景均可)
三、高级方案:background-clip文本裁剪
原理:利用background-clip: text将背景裁剪到文字区域,结合text-fill-color实现镂空。
.text{
color: transparent; /* 或使用text-fill-color */
-webkit-text-fill-color: transparent;
background: url(../images/back.jpg) center/cover; /* 任意背景 */
-webkit-background-clip: text;
background-clip: text;
}
扩展:动态视频背景
.video-box{
position: relative; /* 作为视频和文字的定位容器 */
}
.video-box video {
position: absolute;
top: 0;
left: 0;
width: 100%;
z-index: -1; /* 视频置于文字下方 */
}
.video-box h1 {
font-size: 6rem; /* 大字体增强效果 */
background: white;
mix-blend-mode: screen; /* 关键:与背景视频混合 */
-webkit-background-clip: text;
background-clip: text; /* 背景仅显示在文字区域 */
color: transparent; /* 文字本身透明 */
}
background-clip: text 让白色背景仅出现在文字形状内。
mix-blend-mode: screen 使文字区域的白色背景与下方视频混合,显示视频内容。
文字本身设置为透明,最终呈现 “视频透过文字显示” 的镂空效果。