table實作表頭固定
HTML
<div style="width: 800px;">
<div class="table-head">
<table>
<colgroup>
<col style="width: 80px;" />
<col />
</colgroup>
<thead>
<tr><th>序号</th><th>内容</th></tr>
</thead>
</table>
</div>
<div class="table-body">
<table>
<colgroup><col style="width: 80px;" /><col /></colgroup>
<tbody>
<tr><td>a</td><td>我隻是用來測試的</td></tr>
<tr><td>b</td><td>我隻是用來測試的</td></tr>
<tr><td>c</td><td>我隻是用來測試的</td></tr>
<tr><td>d</td><td>我隻是用來測試的</td></tr>
<tr><td>e</td><td>我隻是用來測試的</td></tr>
</tbody>
</table>
</div>
</div>
CSS
.table-head{padding-right:17px;background-color:#999;color:#000;}
.table-body{width:100%; height:300px;overflow-y:scroll;}
.table-head table,.table-body table{width:100%;}
.table-body table tr:nth-child(2n+1){background-color:#f2f2f2;}
備注
其實關鍵之處在于
1、使用了colgroup标簽,來對上下兩個表格的列寬進行了定義,讓他們保持一緻。
2、上邊的div .table-head添加了樣式padding-right:17px,這個寬度是為了保證跟下邊的div .table-body的滾動條保持一緻,同時下邊的表格.table-body添加了樣式overflow-y:scroll;
隻要保證上述兩點的話,你也可以做出固定表頭的表格來,同時不會發生上下的列不對齊的問題,屢試不爽!