如何实现文本背景高度与文本居中对齐的效果?
解决方案
要实现白色背景块相对于文本垂直居中且高度小于文本的效果,可以通过伪元素结合定位来实现,修改后的代码如下:
CSS 代码
body, html{ background:black; margin: 0; padding: 20px; /* 增加内边距方便预览效果 */ } .text-format { display: inline-block; padding-left: 40px; position: relative; } .text-format::before { content: ''; position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 280px; height: 40px; /* 可根据需求调整背景高度 */ background-color: white; z-index: -1; /* 将背景置于文字下方 */ } .text-format span { font-family: 'SimplonBP Bold', Courier, monospace; font-size: 70px; color: #00d318; }
HTML 代码
<div class="text-format"><span>Stacqé</span></div>
实现原理
- 给
.text-format设置position: relative,为伪元素提供定位基准 - 使用
::before伪元素创建独立的白色背景块,通过position: absolute脱离文档流 - 利用
top: 50%和transform: translateY(-50%)让背景块相对于文本垂直居中 - 通过
z-index: -1确保背景块显示在文字下方,避免遮挡文本 - 可根据需求调整伪元素的
height值,控制白色背景的高度
内容的提问来源于stack exchange,提问作者Sudo Sur
相关产品推荐
相关产品推荐

