2019/02/12

position:stickyでスクロール可能なテーブルの行・列ヘッダを固定する

テーブルに表示する情報が多いとき、行ヘッダや列ヘッダを固定して表示したいときがある。そんなときにはposition: stickyを使うと簡単に実装できる。
ただしIEは対応していないため、ポリフィルが必要となる。

完成予想イメージは以下のとおり。



position: stickyでヘッダを固定する


<main class="wrapper">
  <table>
    <thead>
      <tr>
        <th></th>
        <th>Column Title</th>
        <th>...</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th>Row Title</th>
        <td>A</td>
        <td>...</td>
      </tr>
      <tr>...</tr>
    </tbody>
  </table>
</main>
.wrapper {
  width: 500px;
  height: 300px;
  overflow: scroll;
}

table {
  table-layout: fixed;
  width: 100%;
}

thead tr th {
  position: sticky;
  top: 0;
}

tbody tr th {
  position: sticky;
  left: 0;
}

このようにtheadのthと、tbodyのthにposition: stickyを指定することで、スクロールしてもタイトルを固定できる。


参考サイト




以上

written by @bc_rikko

0 件のコメント :

コメントを投稿