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

如何使用Tailwind CSS用div+h2实现<fieldset>+<legend>带标题边框效果

非表单场景下用Tailwind CSS复刻fieldset内嵌标题效果

无需自定义Tailwind配置,仅用原生工具类,通过「外层容器相对定位+标题绝对定位偏移+背景遮挡边框」的逻辑,即可实现和<fieldset>+<legend>完全一致的视觉效果,适配代码如下:

<!DOCTYPE html>
<html lang='zh-CN'>
<head>
<meta charset='UTF-8' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<link href='tailwind.css' rel='stylesheet'>
</head>
<body class='p-3 bg-white'>
<!-- 原生fieldset效果对比 -->
<fieldset class='p-3 border border-black'>
  <legend>A Legend Title</legend>
  Blah blah. Blah blah.
</fieldset>

<!-- div+h2实现同等效果 -->
<div class='p-3 border border-black relative mt-6'>
  <h2 class='absolute -top-3 left-2 px-1 bg-white text-base font-normal'>A Heading</h2>
  Blah blah. Blah blah.
</div>
</body>
</html>

原生fieldset与自定义div实现效果对比
关键样式说明:

  • 外层div新增relative类:设置相对定位,作为内部标题的定位参照
  • h2新增absolute -top-3 left-2类:将标题向上偏移12px,左侧留8px边距,对齐原生legend的默认位置
  • h2新增px-1 bg-white类:给标题加左右内边距,背景设为和页面一致的白色,刚好遮挡住外层div的上边框,模拟标题嵌入边框的效果
  • h2新增text-base font-normal类:重置h2默认的大号加粗样式,和原生legend的默认字体样式对齐,可根据设计需求自行调整

如果页面使用非白色背景或者深色模式,只要把h2的bg-white替换为和外层容器背景一致的类即可适配,其余样式无需改动。

内容的提问来源于stack exchange,提问作者CW Holeman II

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:39:03