11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CSSのposition: stickyでテーブルのヘッダー行・列を固定してborderもいい感じに

Last updated at Posted at 2020-04-24

これは何

CSSのposition: sticky;だけででテーブルヘッダを固定できると聞いて感激し
border-collapse: collapse;だと枠線が変になることに絶望して
collapseぽく使えるようにした

ブツ

table.sticky-header {
  border-collapse: separate;
  border-spacing: 0;  /* ここ */
}
table.sticky-header:not(.not-vertical-sticky) > thead > tr > th {
  position: sticky;
  top: 0;
  z-index: 2;
}
table.sticky-header:not(.not-horizontal-sticky) > thead > tr > th:first-child {
  position: sticky;
  left: 0;
  z-index: 3;
}
table.sticky-header:not(.not-horizontal-sticky) > tbody > tr > th:first-child {
  position: sticky;
  left: 0;
  z-index: 1;
}

/* ここ */
table.sticky-header > thead + tbody > tr > th,
table.sticky-header > thead + tbody > tr > td {
  border-top: none;
}
table.sticky-header > thead > tr:not(:first-child) > th,
table.sticky-header > thead > tr:not(:first-child) > td,
table.sticky-header > tbody > tr:not(:first-child) > th,
table.sticky-header > tbody > tr:not(:first-child) > td {
  border-top: none;
}
table.sticky-header > thead > tr > th:not(:first-child),
table.sticky-header > thead > tr > td:not(:first-child),
table.sticky-header > tbody > tr > th:not(:first-child),
table.sticky-header > tbody > tr > td:not(:first-child) {
  border-left: none;
}

table thead tr th,
table thead tr td,
table tbody tr th,
table tbody tr td {
  border: 10px solid red; /* あとは好みで普通にボーダーを適用させるだけ */
}

SCSS版はここに置きました
https://github.com/umenosuke/tslib/blob/master/src/html/table/_stickyHeader.scss

説明

border-collapse: separate;のまま
border-spacing: 0;で隙間をなくし
重複してしまうborderをnoneにして対応

theadがあってもいいし無くてもいいように
上側のborderをnoneにするところはゴニョゴニョ

classのつけ外しで水平&垂直のstickyをそれぞれ有効/無効にできるようにしてます

参考

CSSのposition: stickyでテーブルのヘッダー行・列を固定する
https://qiita.com/orangain/items/6268b6528ab33b27f8f2

11
10
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
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?