表示例
列ヘッダー行ヘッダー | 1列目 | 2列目 |
---|---|---|
1行目 | セル | セル |
2行目 | セル | セル |
※Internet Explorer 11では表示できません。
動作確認 | Edge Chrome Firefox |
---|
サンプルソース
<style>
.diagonal tr:first-child th:first-child {
background-image: linear-gradient(
to right top, transparent calc(50% - 0.5px), #eaeaea 50%, #eaeaea calc(50% + 0.5px), transparent calc(50% + 1px)
);
display: grid;
width: max-content;
justify-content: space-between;
grid-template-columns: repeat(2, 1fr);
grid-auto-rows: 1fr;
}
.col-header {
grid-column-start: 2;
text-align: right;
}
.row-header {
grid-column-start: 1;
}
</style>
<table class="diagonal">
<tr><th><span class="col-header">列ヘッダー</span><span class="row-header">行ヘッダー</span></th><th>1列目</th><th>2列目</th></tr>
<tr><th>1行目</th><td>セル</td><td>セル</td></tr>
<tr><th>2行目</th><td>セル</td><td>セル</td></tr>
</table>
CSSの最初の行、「tr:first-child th:first-child」にてテーブルの左上のセルを指定しています。
background-image行にて斜線を引いています。linear-gradientの最初の引数「to right top」は、セルの左下から右上にグラデーションをかけます。このグラデーションを「背景の色」「線の色」「背景の色」の3段階とすることで、斜線を表現します。
2、5番目の引数の前半は、背景の色指定です。2番目は斜線より左下、5番目は右上になります。transparentは、セルの色指定をそのまま出します。
3、4番目の引数の前半は、線の色指定です。テーブル枠の色指定に合わせてください。(#eaeaeaは、このブログのテーブル枠の色です)
display行からは、テキスト配置に関するものです。
HTMLの該当セルでは、列ヘッダー、行ヘッダーの順に記述してください。
リファレンス
How to create a cell for row header and column header
https://stackoverflow.com/questions/51278969/how-to-create-a-cell-for-row-header-and-column-header
基本的な考え方は、ここを参考にしました。
【html/CSS】tableのマスに斜線を引く方法
https://csshtml.work/table-shasen/
きれいに斜線を引く方法と、任意のセルに斜線を引く方法について解説しています。
Using grid to split a table cell
https://www.peterkrautzberger.org/0213/
きれいにテキストを配置する方法と、SVGを使って斜線を引く方法について解説しています。