如何同时为文字添加背景图、描边和阴影并调整层级?
解决text-shadow置于背景图下方的问题
问题说明
给文字添加背景图、文字描边和阴影时,text-shadow会显示在背景图上方,需要将阴影调整到背景图下方。
解决方案
由于-webkit-background-clip: text的渲染层级高于text-shadow,无法直接通过原生属性调整层级。可以通过伪元素分离阴影和文字内容,实现阴影在背景图下方的效果:
修改后的代码
CSS
.letsgo { font-family: Catamaran, sans-serif; font-size: 10em; background-image: url(https://files.cargocollective.com/c2106023/Unavngivet.png); background-size: contain; -webkit-text-fill-color: transparent; -webkit-background-clip: text; -moz-background-clip: text; -webkit-text-stroke: 1px #fff; text-decoration: none; position: relative; } .letsgo::after { content: attr(data-text); position: absolute; top: 0; left: 0; z-index: -1; -webkit-text-fill-color: transparent; -webkit-text-stroke: 0; text-shadow: 2px 2px 6px #CE5937, 8px 10px 6px #3D79CE, 8px 3px 2px #D782A5; }
HTML
<!DOCTYPE html> <html> <head> <style> /* 上述CSS代码 */ </style> </head> <body> <a class="letsgo" data-text="here is my text">here is my text</a> </body> </html>
原理说明
- 原元素保留背景图、文字描边和透明文字填充,作为上层显示内容
- 伪元素通过
attr(data-text)复制原文字内容,仅保留阴影效果,通过z-index: -1将其置于原元素下方,从而让阴影显示在背景图之后 - 使用
data-text属性确保伪元素与原元素文字内容一致,避免重复编写文本
内容的提问来源于stack exchange,提问作者NoCSStoday
相关产品推荐
相关产品推荐

