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

使用fieldset和legend实现文字居中分隔线效果失败求助

解决文字居中于横线的问题

我懂你想用fieldset和legend实现文字卡在横线中间的效果,不过目前的代码因为浏览器对这两个元素的默认样式处理,导致没达到预期——应该是文字位置不对,横线还有缩进,甚至文字底下还露着横线对吧?咱们来调整一下:

修正后的fieldset/legend方案

CSS代码

.faleConosco {
  width: 100vw;
}

.faleConosco fieldset {
  border-top: 1px solid #333;
  border-bottom: none;
  border-left: none;
  border-right: none;
  display: block;
  text-align: center;
  /* 去掉浏览器默认的padding,避免横线左右缩进 */
  padding: 0;
  /* 让fieldset在容器中水平居中,可选调整宽度避免太宽 */
  margin: 0 auto;
  width: 90%;
}

.faleConosco fieldset legend {
  padding: 0 10px;
  /* 强制legend水平居中,抵消默认的定位偏移 */
  margin: 0 auto;
  /* 用背景色盖住下面的横线,要和页面背景色一致 */
  background-color: #fff; /* 替换成你的页面实际背景色 */
}

HTML代码

<section class="faleConosco">
  <fieldset>
    <legend>Produtos</legend>
  </fieldset>
</section>

为啥原来的代码没生效?

  • 浏览器默认给fieldset加了内边距,导致横线左右两边缩进,看起来不是贯穿的效果
  • legend的默认定位是偏顶部且不会自动居中,必须手动设置margin: 0 auto才能让它在横线中间
  • 没给legend设置背景色,导致它下面的横线会透出来,破坏文字“卡在”横线中间的视觉感

更灵活的替代方案(不用fieldset/legend)

如果不想纠结表单元素的默认样式,用伪元素实现会更灵活,兼容性也更好:

CSS代码

.title-divider {
  position: relative;
  text-align: center;
  width: 90%;
  margin: 20px auto;
}

.title-divider::before,
.title-divider::after {
  content: "";
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 40%; /* 可调整横线长度 */
  height: 1px;
  background-color: #333;
}

.title-divider::before {
  left: 0;
}

.title-divider::after {
  right: 0;
}

.title-divider span {
  padding: 0 15px;
  background-color: #fff; /* 和页面背景色一致 */
}

HTML代码

<section class="faleConosco">
  <div class="title-divider">
    <span>Produtos</span>
  </div>
</section>

这个方案可以轻松调整横线的长度、颜色,或者文字的间距,完全不用考虑表单元素的默认样式限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 10:45:28