如何在带sticky顶部导航的溢出父容器内实现表格表头吸顶
容器内表格表头吸附在sticky导航下方的实现方案
- 先确认顶部导航的配置:给sticky导航设置
top: 0以及高于表头的z-index,同时明确导航的高度数值,后续表头的top偏移要和这个高度对齐。比如导航高度为16个Tailwind单位(即64px),导航类配置为sticky top-0 z-20 h-16 - 配置表格的滚动容器:给包裹表格的外层容器设置纵向滚动属性和最大高度,最大高度需要减去导航的高度,避免内容被导航遮挡,对应类为
overflow-y-auto max-h-[calc(100vh-64px)] - 配置表头吸附样式:给thead内所有th元素设置sticky定位,top值等于导航高度,同时设置低于导航的z-index和不透明背景,避免内容透显,对应类为
sticky top-16 z-10 bg-white
注意事项:如果你的导航高度是动态值,可以用CSS变量统一管理导航高度和表头的top偏移,避免两边修改不一致的问题。
参考代码示例
<!-- 顶部sticky导航 --> <nav class="sticky top-0 z-20 h-16 bg-slate-800 text-white px-6 flex items-center"> 站点导航 </nav> <!-- 表格滚动外层容器 --> <div class="overflow-y-auto max-h-[calc(100vh-64px)] px-6 py-4"> <table class="w-full border-collapse"> <thead> <tr> <th class="sticky top-16 z-10 bg-white p-4 text-left border-b font-medium">ID</th> <th class="sticky top-16 z-10 bg-white p-4 text-left border-b font-medium">名称</th> <th class="sticky top-16 z-10 bg-white p-4 text-left border-b font-medium">操作</th> </tr> </thead> <tbody> <tr> <td class="p-4 border-b">1</td> <td class="p-4 border-b">测试数据1</td> <td class="p-4 border-b">编辑</td> </tr> <!-- 更多表格行 --> </tbody> </table> </div>
内容的提问来源于stack exchange,提问作者MissJulie
相关产品推荐
相关产品推荐

