次のようなhtmlでヘッダーを固定したいときのメモ
次の感じの表のヘッダーのみ固定してスクロールできるようにしたかった。
# 項目1のみ縦3行結合した表 <div class="target-data"> <table class="table"> <thead> <tr> <th>項目1</th> <th>項目2</th> <th>項目3</th> <th>項目4</th> <th>項目5</th> </tr> </thead> <tbody> <tr> <td rowspan="3">値1</td> <td>値2</td> <td>値3</td> <td>値4</td> <td>値5</td> </tr> </tbody> </table> </div>
cssを次のようにする
# 親要素にスクロールを設定(overflow-y: scroll;) .target-data { display: block; height: 500px; overflow-y: scroll; } # ヘッダーを固定(position: sticky;) .target-data table thead { display: table; top: 0px; width: 100%; table-layout: fixed; position: sticky; } .target-data table tbody { display: table; width: 100%; table-layout: fixed; }
参考
WEBブログ | テーブルの行や列を固定しスクロールする方法 | RunLand(ランランド)株式会社
CSSでテーブル表の一部を固定してスクロールする方法 | 福岡のホームページ制作会社 | シンス株式会社