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

如何为<hr>元素添加背景色且不影响相邻文本?

解决
添加周围背景色的问题

你可以试试这两种方法,都能实现黄色高亮水平线的效果,且不会影响相邻文本:

方法一:用带内边距的div包裹并调整
样式

默认<hr>的margin和border样式会让包裹它的div背景仅显示在细线区域,给div加上下内边距,同时重置<hr>的默认样式,就能让背景色覆盖到线条周围:

test
<div style="background-color: yellow; padding: 4px 0;">
  <hr style="margin: 0; border: none; height: 1px; background-color: #333;">
</div>
test
  • 给div设置padding: 4px 0,让黄色背景在水平线上下留出空间
  • 重置<hr>的margin: 0消除默认间距,用height:1px和background-color定义线条样式

方法二:用伪元素给
添加背景

不用额外的div,直接通过<hr>的伪元素实现背景效果,更简洁:

test
<hr style="position: relative; border: none; height: 1px; background-color: #333;">
test

对应的CSS(可放在<style>标签中):

hr::before {
  content: '';
  position: absolute;
  top: -4px;
  left: 0;
  right: 0;
  bottom: -4px;
  background-color: yellow;
  z-index: -1;
}
  • 给<hr>设置position: relative,让伪元素能基于它定位
  • 伪元素设为绝对定位,覆盖<hr>上下各4px的区域,背景色设为黄色,z-index: -1让它在线条下方,不会遮挡线条

内容的提问来源于stack exchange,提问作者Linux in a Bit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 21:44:56