Bootstrap实现表格内容超出Div高度时显示垂直滚动条
实现Bootstrap表格内容超出容器时显示垂直滚动条
要让右侧两个Div内的表格在内容过多时显示垂直滚动条,同时保持表头固定,可按以下步骤修改:
1. 调整HTML结构
将表格的<tbody>包裹在自定义容器内,确保结构清晰便于样式控制:
<div class="container-fluid"> <div class="row"> <!-- ********** 棋盘 ********** --> <div id="board" class="col-sm-6 board m-3 shadow"> <!-- 通过board JS创建 --> </div> <!-- ********** 走棋记录 ********** --> <div id="move-list" class="col-sm-2 m-3 bg-light shadow"> <table class="table table-striped caption-top table-fixed"> <caption class="text-center fw-bold">走棋记录</caption> <thead class="table-light"> <tr> <th scope="col">#</th> <th id="light-player-name" scope="col">玩家1</th> <th id="dark-player-name" scope="col">玩家2</th> </tr> </thead> <div class="table-body-scroll"> <tbody> <tr> <th scope="row">1</th> <td>♙f3</td> <td>♟︎e5</td> </tr> <tr> <th scope="row">2</th> <td>♘cr</td> <td>♞c6</td> </tr> <tr> <th scope="row">3</th> <td>♙f4</td> <td>♟︎exf4</td> </tr> <!-- 可添加更多行测试滚动效果 --> </tbody> </div> </table> </div> <!-- ********** 在线玩家列表 ********** --> <div id="online-list" class="col-sm-2 m-3 bg-light shadow"> <table class="table table-striped caption-top table-fixed"> <caption class="text-center fw-bold">在线玩家列表</caption> <thead class="table-light"> <tr> <th scope="col">#</th> <th scope="col">用户名</th> </tr> </thead> <div class="table-body-scroll"> <tbody> <tr> <th scope="row">1</th> <td>@username</td> </tr> <tr> <th scope="row">2</th> <td>@username</td> </tr> <tr> <th scope="row">3</th> <td>@username</td> </tr> <!-- 可添加更多行测试滚动效果 --> </tbody> </div> </table> </div> </div> </div>
2. 添加自定义CSS样式
通过CSS控制滚动容器高度、表格布局,确保表头固定且列对齐:
/* 固定表格布局,保证列宽一致 */ .table-fixed { table-layout: fixed; width: 100%; } /* 滚动容器设置最大高度和垂直滚动 */ .table-body-scroll { max-height: 400px; /* 可根据需求调整高度 */ overflow-y: auto; display: block; } /* 表头保持固定,不随滚动移动 */ .table-fixed thead { display: table; width: 100%; } /* 表格tbody设置宽度,与表头对齐 */ .table-fixed tbody { display: table; width: 100%; } /* 可选:调整滚动条样式,适配Bootstrap风格 */ .table-body-scroll::-webkit-scrollbar { width: 6px; } .table-body-scroll::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 3px; } .table-body-scroll::-webkit-scrollbar-thumb { background: #adb5bd; border-radius: 3px; } .table-body-scroll::-webkit-scrollbar-thumb:hover { background: #6c757d; }
关键说明
max-height:设置滚动容器的最大高度,超出此高度时自动显示垂直滚动条,可根据页面布局需求调整数值。table-layout: fixed:强制表格列宽均匀分配,避免表头与滚动内容的列错位。- 将
<tbody>包裹在display: block的容器中,才能实现垂直滚动效果,同时表头保持display: table固定在顶部。
内容的提问来源于stack exchange,提问作者VictoRPiles
相关产品推荐
相关产品推荐

