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

如何在h1标题内正确定位CSS伪元素实现指定文本高亮效果

CSS局部文本高亮伪元素宽度异常修复方案

问题原因

当前伪元素拉伸到整个标题宽度的核心原因是:你给伪元素设置了position: absolute绝对定位,但包裹目标文本的span.yellow-highlight默认是static定位,绝对定位元素的尺寸会默认基于最近的非static定位祖先元素计算,因此伪元素的width: 100%会按照h1标签甚至页面宽度计算,才会出现不符合预期的拉伸效果。

解决方法

只需要给.yellow-highlight类添加position: relative属性,让伪元素的定位基准变为包裹目标文本的span本身,100%宽度就会自动匹配「Piece of Cake」的文本长度,仅覆盖目标内容,不会影响标题其他部分。

修改后完整代码

CSS代码

.yellow-highlight {
  white-space: nowrap;
  /* 新增相对定位,作为伪元素的定位基准 */
  position: relative;
}

.yellow-highlight:before {
  content: " ";
  position: absolute;
  width: 100%;
  height: 1em;
  left: -0.25em;
  top: 0.1em;
  padding: 0 0.25em;
  background-color: #FEFDBD;
  transform: rotate(-2deg);
  z-index: -1;
}

HTML代码无需调整,保持原有结构即可:

<h1>Blah Blah Blah Blah Blah Blah Blah <span class="yellow-highlight">Piece of Cake</span></h1>

内容的提问来源于stack exchange,提问作者TinyTiger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:09:04