HTMLのtableタグ、およびCSSのdisplay:table;を使ったレイアウト実装時に、テーブルのセルを[position:sticky;]で固定すると、そのセルのボーダーが消えてしまう現象の解決方法を紹介します。
まずはエラーが発生する状況をご確認ください。
DEMO : テーブルのボーダーが消える現象
解決方法
この現象は親要素のtableにborder-collapse:collapse;を指定しているときに発生します。
つまり。親要素のtableに対して[border-collapse:separate;]を指定すると、ボーダーが正常に表示されるようになります。
HTMLサンプル
<div class="responsive-table"> <table> <tr> <th class="fixed-cell">サンプル</th> <th>サンプル</th> <th>サンプル</th> <th>サンプル</th> </tr> <tr> <th class="fixed-cell">サンプル</th> <td>サンプル</td> <td>サンプル</td> <td>サンプル</td> </tr> </table> </div>
ここでは「class="fixed-cell"」と名付けたテーブルセルを左側に固定すると仮定します。
CSSサンプル
.responsive-table {
padding:0;
margin:0 0 6em 0;
overflow:auto;
white-space:nowrap;
}
table {
border-collapse:separate;
border-spacing:0;
width:auto;
}
table th,
table td {
background-color:#fff;
border-right:1px solid olivedrab;
border-bottom:1px solid olivedrab;
padding:1em;
white-space:nowrap;
}
table tr:first-child th,
table tr:first-child td {
border-top:1px solid olivedrab;
}
table th:first-child,
table td:first-child {
border-left:1px solid olivedrab;
}
table th.fixed-cell,
table td.fixed-cell {
position:-webkit-sticky;
position:sticky;
left:0;
min-width:60px;
width:60px;
}
先ほどHTML側で「class="fixed-cell"」と名付けたテーブルセルにposition:sticky;を効かせ、さらに親要素のtableタグにborder-collapse:separate;を指定しました。
これでボーダーが消える現象を回避できます。
DEMO : テーブルのボーダーが消える現象の解決方法
補足
[border-collapse:separate;]を指定しているにも関わらず、横スクロール発生時にborderが消えてしまうケースがあります。
これはtable要素に対してborderを指定していることが原因です。
table-cellである「th」または「td」に対してborderを指定すると解決します。
ぜひお試しください。
こちらの書籍は初学者のウェブデザイナーの方々にオススメです。
↓