CSSでテーブルにカウンタを付ける・列幅に自由に対応したテーブル
要約 : 行(tr)にCSSの「counter-increment」を利用してカウンタを付ける。更に、行内の列(td)にも連番を入れています。簡単な規則宣言(設置、加算、表示)で表示出来ます。
テーブルに2つのクラスを設定し、1つ目はサイト全体の構造で列数は個別に設定する。列幅は2つ目のクラスを指定することで、テーブル作成が手間をかけずに設置出来ます。
連番 | ひらがな | カタカナ | 英大文字 | 英小文字 |
---|---|---|---|---|
あいうえお | アイウエオ | AIUEO | aiueo | |
かきくけこ | カキクケこ | KAKIKUKEKO | kakikukeko | |
さしすせそ | サシスセソ | SASHISUSESO | sashisuseso | |
たちつてと | タチツテト | TACHITHUTETO | tachithuteto | |
なにぬねの | ナニヌネノ | NANINUNENO | naninuneno |
html記述 2つ目のクラス(tbl_a)で列幅を設定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!-- html --> <table class="table_base tbl_a"> <tr> <th>連番</th> <th>ひらがな</th> <th>カタカナ</th> <th>英大文字</th> <th>英小文字</th> </tr> <tr> <td>.</td> <td>あいうえお</td> <td>アイウエオ</td> <td>AIUEO</td> <td>aiueo</td> </tr> <!-- 中間省略 --> </table> |
css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/* css */ /* 1つ目のクラス・テーブルの基本構造 */ .table_base { border-collapse: collapse; /* 隣接するセルの罫線を重ねる */ table-layout:fixed; /* 列幅を固定レイアウト */ width:100%;} /* 全体の幅:100% */ .table_base th{ /* 列見出し */ border:1px solid #000;} /* 罫線付き */ .table_base tr td:nth-of-type(n+2){ /* 列2番目から最後迄 */ padding-left:5px;} /* 先頭にスペース */ .table_base tr:nth-of-type(n+2) /* 2行目から最後迄 */ td:first-of-type { /* 1列目 */ text-align:center;} /* 中央配置 */ /* 2つ目のクラス・列幅の設定 最初の列 */ .tbl_a tr th:first-of-type{ /* 最初の列 */ width:8%;} /* 列幅 */ /* 行へのカウンタの設置・加算・表示 */ .table_base{counter-reset: ctr;} /* 名前を ctr として初期0で設定 */ .table_base tr:nth-of-type(n+2){ /* 2番目から最後まで */ counter-increment: ctr;} /* ctr にプラス1 */ .table_base tr td:first-of-type::before{ /* 列の1番目に */ content:counter(ctr); /* カウンタ(ctr)を表示 */ display: block; /* 以降はカウンタ表示の修飾 */ margin:0 auto; font-weight:bold; font-size:1.05em; background-color: #cf0; line-height:22px; width: 22px; border:1px solid #000; /* padding-left:2px; カウンタ値が左に寄るので微調整 20190901 無効化 */ border-radius: 50%;} /* 行内の列へのカウンタの設置・加算・表示 */ .table_base tr{counter-reset: ctr_td;} .table_base tr:nth-of-type(n+2) td:nth-of-type(n+2){ counter-increment: ctr_td;} .table_base tr td:nth-of-type(n+2)::before{ content:counter(ctr_td)") ";} |
- Line
- 説明
- 3-8
- テーブルの基本構造と罫線設定
- 9-13
- 表示内容の体裁を整える部分なので、記述しなくても可。
- 16-17
- カウンタ値の列幅設定。残り4列は均等幅なので、テーブルの自動設定に。
- 20-24
- カウンタの設置・加算・表示。コメントを参照下さい。
- 25-34
- カウンタ表示の修飾なので、記述しなくても可。
- 37-
- 行単位で列に連番を付けるCSSです。あまり利用しないと思いますが、参考までに。行で初期化しているのがポイントです。