LoginSignup
10
11

More than 5 years have passed since last update.

【css】テーブルのヘッダを固定する方法

Posted at

テーブル要素の行とか列とかを、スクロースしても固定されたままにしたい時はどうすればいいか。
2通りのやり方を学んだのでまとめておきます

1 tbodyをブロック要素にする

tbody {
  display:block;
overflow-y:scroll;
  height:100px;
}
tbody{
  overflow-y:scroll;
  height:100px;
}

ブロック要素にする都合上、高さは明示してあげる必要があります。

2 position:sticky をつかう


table {
    display: block;
    overflow: scroll;
    height: 100px;
    table-layout: fixed;
}

thead,
tbody {
  display: block;
}

th, td {
  display: inline-block;
}

thead {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  z-index: 2;
}

モダンな感じがするやり方
ブラウザによっては対応してなかったり、ヘッダとセルの字や背景が重なるのが面倒だったりする点は注意

10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11