Bootstrap 不支持原生固定表头,需对每个 设置 position: sticky; top: 0 并包裹带 max-height 和 overflow-y: auto 的容器,同时注意 Safari 兼容性及复杂表格场景推荐使用专业库。

Bootstrap 本身不提供原生的「固定表头」(sticky header)表格组件,table 在滚动时表头不会自动悬浮;必须手动干预 CSS 或借助少量 JS,否则在 .table-responsive 容器里一滚动,表头就消失。
为什么 .table-responsive 不够用
它只是给表格加了个横向滚动容器,对纵向滚动无约束,且 <thead> 默认随整个 <code>table 一起滚动。常见错误是以为套个 div class="table-responsive" 就能固定表头——实际完全没效果。
-
position: sticky对<thead> 无效(浏览器不支持直接对 <code><thead> 设 <code>sticky) - Bootstrap 5+ 的
.table类未包含任何滚动隔离逻辑 - 若表格行数多、内容高,单纯设
max-height会导致<tbody> 溢出而表头仍不固定<h3>用 <code>position: sticky+<th> 单独控制(推荐)<p>核心思路:放弃对 <code><thead> 整体设 sticky,改为对每个 <code><th> 设置 <code>position: sticky; top: 0,并确保父容器有明确高度和overflow-y: auto。- 必须给
<table> 外层包一层带 <code>max-height和overflow-y: auto的div - 每个
<th> 需设 <code>position: sticky; top: 0; background: white; z-index: 10(否则滚动时文字被盖住) - 为避免列宽错乱,建议所有
<th> 和 <code><td> 显式设 <code>min-width或用table-layout: fixed - Bootstrap 的
.table类可保留,但需额外覆盖默认样式
<div style="max-height: 400px; overflow-y: auto;"> <table class="table table-sm"> <thead> <tr> <th style="position: sticky; top: 0; background: #fff; z-index: 10; min-width: 120px;">ID</th> <th style="position: sticky; top: 0; background: #fff; z-index: 10; min-width: 200px;">用户名</th> <th style="position: sticky; top: 0; background: #fff; z-index: 10; min-width: 150px;">状态</th> </tr> </thead> <tbody> <tr><td>1</td><td>admin</td><td>active</td></tr> <!-- 更多行... --> </tbody> </table> </div>兼容性与移动端适配要点
Chrome/Firefox/Edge 均支持
position: sticky,但 Safari(尤其 iOS ≤14.5)对table内部元素支持不稳定,容易失效。- 不要依赖
sticky在 iOS 旧版 Safari 上工作,可降级为 JS 监听滚动后动态切换fixed类 - 移动端小屏下,列太多会挤在一起,建议配合
.table-responsive做横向滚动,同时保持纵向 sticky —— 即外层再套一层div.table-responsive - 如果用了 Bootstrap 5 的
data-bs-spy="scroll"或其他滚动插件,可能干扰sticky行为,优先关闭或隔离作用域
真正麻烦的不是写法,而是当表格有合并单元格(
rowspan/colspan)、动态列宽计算、或嵌入了input/select表单控件时,sticky容易错位或遮挡。这种场景下,不如直接用DataTable或AG Grid这类专业表格库——它们内置了 robust 的固定表头逻辑,比手搓 CSS 更省心。 - 必须给


















