position: sticky;でtableを下スクロール時はヘッダ、横スクロール時は最左を固定

Ads

Result


position: sticky;を使ったスプレッドシートライクなtableのサンプル。

css

.table-wrapper {/*table全体のラッパー。スクロールを表示する*/
  max-width: 500px;
  overflow: scroll;
}

table {
  position: relative;
  border: 1px solid #ddd;
  border-collapse: collapse;
}

td, th {
  white-space: nowrap;
  border: 1px solid #ddd;
  padding: 20px;
  text-align: center;
}

th {
  background-color: #eee;
  position: sticky;
  top: -1px;
  z-index: 2;
}

th:first-of-type {
  left: 0;
  z-index: 3;
}

tbody tr td:first-of-type {/*最初の要素を固定する*/
  background-color: #eee;
  position: sticky;
  left: -1px;
  text-align: left;
}

html

<div class="table-wrapper">
  <table>
  <thead>
    <tr>
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
  .
  .
  .
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>和歌山</td>
      <td>1</td>
      <td>1</td>
  .
  .
  .
</table>
</div>

can i use

via

A Simple Responsive Spreadsheet

タイトルとURLをコピーしました