You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现文本背景高度与文本居中对齐的效果?

解决方案

要实现白色背景块相对于文本垂直居中且高度小于文本的效果,可以通过伪元素结合定位来实现,修改后的代码如下:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 11:55:10