対象とするテーブルではヘッダ部をthead要素内に記述し、ボディ部と分離しておきます。
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
theadとtbodyをブロック要素とし、tbodyのoverflowをscrollとします。
<style type="text/css">
thead, tbody {
display: block;
}
tbody {
overflow-x: hidden;
overflow-y: scroll;
height: 100px;
}
</style>
このoverflowをautoとした場合、Internet ExplorerやFirefoxではスクロールバーが右端のセルに重なってしまいます。
| overflow-x: hidden; overflow-y: scroll; |
overflow-x: hidden; overflow-y: auto; |
overflow: auto; | ||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
|
またtheadとtbodyをブロック要素とすると、セルの内容によっては幅が合わなくなるため、
| AAA | BB |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
それらの幅が合うように、各列の幅を指定します。
th, td {
width: 100px;
}
| AAA | BB |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
ヘッダ部を他のテーブルに分離し、ボディ部をブロック要素内に配置する方法でも、ヘッダから独立してスクロールさせられます。
<table>
<tr>
<th>A</th>
<th>B</th>
</tr>
</table>
<div>
<table>
<tr>
<td>1</td>
<td>1</td>
</tr>
</table>
</div>
<style type="text/css">
th, td {
width: 100px;
}
div {
width: 250px;
height: 100px;
overflow: auto;
}
</style>
| AAA | BBB |
|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |