1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width"> 6 <title>固定表头</title> 7 <style type="text/css"> 8 #table-container{ 9 border:1px solid black; 10 width:316px; 11 } 12 13 table{width:300px;} 14 15 .table-header{ 16 padding-left:10px; 17 color:white; 18 background-color:grey; 19 } 20 21 .table-body{ 22 height:200px; 23 overflow-y:scroll; 24 overflow-x:hidden; 25 } 26 27 .table-body td{padding-left:15px;} 28 </style> 29 </head> 30 <body> 31 <div id="table-container"> 32 <div class="table-header"> 33 <table> 34 <colgroup> 35 <col style="80px;"/> 36 <col style="80px;"/> 37 <col style="80px;"/> 38 </colgroup> 39 <th>标题1</th> 40 <th>标题2</th> 41 <th>标题3</th> 42 </table> 43 </div> 44 <div class="table-body"> 45 <table> 46 <colgroup> 47 <col style="80px;"/> 48 <col style="80px;"/> 49 <col style="80px;"/> 50 </colgroup> 51 52 <tr> 53 <td>content</td> 54 <td>content</td> 55 <td>content</td> 56 </tr> 57 <tr> 58 <td>content</td> 59 <td>content</td> 60 <td>content</td> 61 </tr> 62 <tr> 63 <td>content</td> 64 <td>content</td> 65 <td>content</td> 66 </tr> 67 <tr> 68 <td>content</td> 69 <td>content</td> 70 <td>content</td> 71 </tr> 72 <tr> 73 <td>content</td> 74 <td>content</td> 75 <td>content</td> 76 </tr> 77 <tr> 78 <td>content</td> 79 <td>content</td> 80 <td>content</td> 81 </tr> 82 <tr> 83 <td>content</td> 84 <td>content</td> 85 <td>content</td> 86 </tr> 87 <tr> 88 <td>content</td> 89 <td>content</td> 90 <td>content</td> 91 </tr> 92 <tr> 93 <td>content</td> 94 <td>content</td> 95 <td>content</td> 96 </tr> 97 <tr> 98 <td>content</td> 99 <td>content</td> 100 <td>content</td> 101 </tr> 102 <tr> 103 <td>content</td> 104 <td>content</td> 105 <td>content</td> 106 </tr> 107 </table> 108 </div> 109 </div> 110 <body> 111 </html>
有几个要点:
<HTML>部分
1.一共有三个div.最外面一个div,包裹住整张表。里面的两个div分别裹住表头和表内容。
2.注意,表格内容也都需要单独的table。表格内容应该是div-table-tr-td.
--------------------------------------------------------------
<CSS>样式部分
3.用到了<colgroup>标签。该标签只能用于table中。方便批量设定列宽;
4.表格内容table-body的div需要设置 (a) 高度; (b) “overflow-y:scroll” 让滚动条出现;