利用::before和::after伪元素可实现多层阴影、背景装饰与立体字效;通过定位与z-index控制层次,结合content:attr()复制文本,能在不增加html标签情况下提升文字视觉表现力。

在css中,伪元素 ::before 和 ::after 不仅能用来插入装饰性内容,还能结合文字阴影和背景效果,实现富有层次感的视觉设计。通过合理使用这两个伪元素,可以在不增加HTML标签的前提下,提升文本的表现力。
利用 ::before 和 ::after 添加多层文字阴影
标准的 text-shadow 属性只能设置一层或多层阴影,但若想实现更复杂的动态或立体效果,可以借助伪元素模拟额外“影子”。
例如,创建一个带有底部偏移阴影的文字效果:
ul { list-style: none; padding: 20px; } li { position: relative; font-size: 24px; color: white; font-weight: bold; } li::before { content: attr(data-text); position: absolute; left: 2px; top: 2px; color: rgba(0,0,0,0.3); z-index: -1; }
这里使用 content: attr(data-text) 复制文本内容,再通过定位偏移形成类似阴影的效果。这种方法比纯 text-shadow 更灵活,可单独控制颜色、透明度甚至模糊度(配合 Filter)。
立即学习“前端免费学习笔记(深入)”;
用伪元素增强背景装饰
想要为文字添加背景边框、渐变底纹或外发光效果,但又不想影响原有布局?::before 或 ::after 可以作为装饰层独立存在。
常见技巧:给文字加一条动态渐变下划线
.highlight { position: relative; display: inline; color: #333; font-size: 20px; } .highlight::after { content: ”; position: absolute; left: 0; bottom: 2px; width: 100%; height: 6px; background: linear-gradient(90deg, #ffcc00, #ff6666); opacity: 0.6; z-index: -1; border-radius: 2px; }
这个例子中,::after 创建了一个位于文字下方的渐变条,看起来像是文字的“背景光带”,不会干扰文本本身的颜色与排版。
组合 before 与 after 实现立体字效
同时使用两个伪元素,可以分别模拟阴影层和高光层,打造浮雕或立体文字效果。
示例:上亮下暗的立体字
.solid-text { position: relative; color: #f3f3f3; font-weight: bold; font-size: 32px; } .solid-text::before { content: attr(data-content); position: absolute; top: 1px; left: 1px; color: #888; z-index: -1; } .solid-text::after { content: attr(data-content); position: absolute; top: -1px; left: 0; color: white; opacity: 0.3; z-index: -2; }
说明:
- ::before 模拟向下偏移的深色“主体投影”
- ::after 添加向上偏移的浅色“高光边缘”
- data-content 存储原始文本,避免在 HTML 中重复写内容
这种叠加方式让文字看起来有厚度,适合标题或强调展示。
基本上就这些技巧。掌握好定位、层级(z-index)和内容复制方法,就能用 ::before 和 ::after 玩出丰富的文字视觉效果,既轻量又高效。


