最稳妥方案是用文字配合CSS绝对定位居中;伪元素方案需用attr(data-text);语义化场景优先。

用 <hr> 加 <span></span> 实现带文字的分割线
纯 HTML 没有原生“带文字的分割线”标签,<hr> 本身只画一条线,文字必须额外加——最稳妥、兼容性最好的做法是把 <hr> 和文字放在同一个容器里,用 CSS 控制布局。
常见错误是直接在 <hr> 标签里写文字(无效),或用 <hr> + 绝对定位文字但没设父容器 position: relative(导致文字飘走)。
推荐结构:
<div class="divider"> <hr> <span>正文开始</span> </div>
对应 CSS(关键点:hr 设为透明边框+背景色,span 覆盖在线上):
立即学习“前端免费学习笔记(深入)”;
.divider {
position: relative;
text-align: center;
}
.divider hr {
border: none;
height: 1px;
background-color: #ccc;
margin: 16px 0;
}
.divider span {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #fff;
padding: 0 12px;
color: #666;
font-size: 14px;
}
CSS ::before/::after 方案更简洁但需注意兼容性
如果不想多写一层 <span></span>,可用伪元素把文字“塞进” <hr> 里,但前提是 <hr> 必须是块级且有明确尺寸。
典型写法:
<hr class="divider-text" data-text="章节分隔">
.divider-text {
position: relative;
border: none;
height: 1px;
background: #ddd;
margin: 24px 0;
}
.divider-text::before {
content: attr(data-text);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #fff;
padding: 0 12px;
color: #777;
font-size: 13px;
}
注意:attr() 只读 HTML 属性,不能读 class 或 id;IE 不支持 attr() 用于非 content 场景(但这里没问题);若文字过长,建议加 white-space: nowrap; overflow: hidden; text-overflow: ellipsis; 防溢出。
用 <fieldset></fieldset> + <legend></legend> 是语义化最优解
如果你的分割线实际用于分组内容(比如表单区块、配置项分段),<fieldset></fieldset> 天然支持带标题的分割线,且语义清晰、无障碍友好。
示例:
<fieldset class="section-divider"> <legend>用户信息</legend> <p>姓名:张三</p> <p>邮箱:zhang@example.com</p> </fieldset>
默认 <legend></legend> 会压在 <fieldset></fieldset> 边框上,要微调样式可:
- 用
legend { width: max-content; margin: 0 auto; }居中 - 用
fieldset { border-top: 1px solid #eee; border-left: 0; border-right: 0; border-bottom: 0; }只留顶线 - 避免用
display: flex直接包裹<legend></legend>,会破坏其定位逻辑
移动端适配和字体大小容易被忽略
文字在分割线上居中,依赖 transform: translate(-50%, -50%),但若父容器缩放(如 viewport 缩放)、或字体用了 rem 且根字体变化,位置可能偏移。
实操建议:
- 给
.divider容器设固定min-height(如min-height: 20px),防止文字被截 - 文字用
px或em,慎用rem,除非你确定根字号稳定 - 在 iOS Safari 上测试时,加
-webkit-appearance: none;到hr,避免某些版本默认样式干扰 - 如果项目用 Tailwind,别硬套
border-t,它不支持中间插文字——老实用flex+absolute手写
真正难的不是画出来,而是让文字始终稳稳骑在线上,尤其在不同设备、不同缩放、不同字体设置下。多测几个真机,比调十遍 CSS 更管用。



















