如何使用CSS实现文字挖空效果,删除文字对应区域的背景图

实现方案
这里提供两种兼容性较好的CSS实现方法,均不需要引入JS:
方法1:使用CSS mask 属性实现(推荐)
利用mask的复合规则,让文字区域对应背景变为透明,其余区域保留背景。
代码示例
<div class="bg-container"> <h2 class="cut-text">DELETE BACKGROUND HERE</h2> </div>
.bg-container { width: 100%; height: 600px; /* 设置需要挖空的背景图 */ background: url("你的背景图链接") center/cover no-repeat; /* mask配置:两层mask重叠区域(文字部分)设为透明 */ mask: linear-gradient(#000, #000), linear-gradient(#000, #000); mask-clip: padding-box, text; mask-composite: exclude; /* webkit内核兼容前缀 */ -webkit-mask: linear-gradient(#000, #000), linear-gradient(#000, #000); -webkit-mask-clip: padding-box, text; -webkit-mask-composite: xor; } .cut-text { font-size: 7rem; font-weight: 900; color: transparent; /* 可自行调整文字位置、字体系列等样式 */ margin: 100px 0 0 50px; }
方法2:使用mix-blend-mode混合模式实现
适合需要兼容低版本浏览器的场景,通过两层元素混合实现挖空效果。
代码示例
<div class="wrapper"> <div class="bg-layer"></div> <h2 class="cut-text">DELETE BACKGROUND HERE</h2> </div>
.wrapper { position: relative; width: 100%; height: 600px; /* 设置文字挖空后要透出的底层背景色/背景图 */ background: #ffffff; } .bg-layer { position: absolute; inset: 0; /* 设置需要挖空的上层背景图 */ background: url("你的背景图链接") center/cover no-repeat; z-index: 1; } .cut-text { position: relative; z-index: 2; font-size: 7rem; font-weight: 900; color: #000; mix-blend-mode: xor; /* 可自行调整文字位置、字体系列等样式 */ margin: 100px 0 0 50px; }
注意事项
- 如果需要调整挖空区域的大小、形状,直接修改文字的字号、字重、内容即可,无需改动背景配置
- 主流浏览器均已支持上述两种属性,针对老旧Webkit内核浏览器添加对应前缀即可正常运行
- 若需要实现多段文字同时挖空,将所有文字节点放在同一个mask容器下即可
内容的提问来源于stack exchange,提问作者Salil Rajkarnikar
相关产品推荐
相关产品推荐

