Bootstrap 如何实现表格(table)头部固定但表格内容可滚动的效果呢?
6.15K 次浏览
3 个回答
-
使用浮动布局实现的方案,如下:
CSS样式:
table { width: 100%; } thead, tbody, tr, td, th { display: block; } tr:after { content: ' '; display: block; visibility: hidden; clear: both; } thead th { height: 30px; } tbody { height: 120px; overflow-y: auto; } thead {} tbody td, thead th { width: 19.2%; float: left; }
示例HTML
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/> <table class="table table-striped"> <thead> <tr> <th>Make</th> <th>Model</th> <th>Color</th> <th>Year</th> </tr> </thead> <tbody> <tr> <td class="filterable-cell">Ford</td> <td class="filterable-cell">Escort</td> <td class="filterable-cell">Blue</td> <td class="filterable-cell">2000</td> </tr> <tr> <td class="filterable-cell">Ford</td> <td class="filterable-cell">Escort</td> <td class="filterable-cell">Blue</td> <td class="filterable-cell">2000</td> </tr> <tr> <td class="filterable-cell">Ford</td> <td class="filterable-cell">Escort</td> <td class="filterable-cell">Blue</td> <td class="filterable-cell">2000</td> </tr> <tr> <td class="filterable-cell">Ford</td> <td class="filterable-cell">Escort</td> <td class="filterable-cell">Blue</td> <td class="filterable-cell">2000</td> </tr> </tbody> </table>
运行效果如图:
-
实现表格(table)头部固定,内容可滚动的效果的方式有多种。
使用纯CSS样式的方式
设置表格头元素(th)的样式为
position: sticky; top: 0;
,如下:.tableFixHead { overflow-y: auto; height: 100px; } .tableFixHead thead th { position: sticky; top: 0; } /* Just common table stuff. Really. */ table { border-collapse: collapse; width: 100%; } th, td { padding: 8px 16px; } th { background:#eee; }
示例HTML如下:
<div class="tableFixHead"> <table> <thead> <tr><th>TH 1</th><th>TH 2</th></tr> </thead> <tbody> <tr><td>A1</td><td>A2</td></tr> <tr><td>B1</td><td>B2</td></tr> <tr><td>C1</td><td>C2</td></tr> <tr><td>D1</td><td>D2</td></tr> <tr><td>E1</td><td>E2</td></tr> </tbody> </table> </div>
效果如下图:
-
自定义一个表格固定的样式类
header-fixed
,示例HTML如下:<table class="table table-striped header-fixed"></table>
定义样式如下:
.header-fixed { width: 100% } .header-fixed > thead, .header-fixed > tbody, .header-fixed > thead > tr, .header-fixed > tbody > tr, .header-fixed > thead > tr > th, .header-fixed > tbody > tr > td { display: block; } .header-fixed > tbody > tr:after, .header-fixed > thead > tr:after { content: ' '; display: block; visibility: hidden; clear: both; } .header-fixed > tbody { overflow-y: auto; height: 150px; } .header-fixed > tbody > tr > td, .header-fixed > thead > tr > th { width: 20%; float: left; }
注意:本示例的列数为5,如果是不同的列数,请修改对应的列宽为
100/列数*100%
。