tableタグを利用する際に意外と知られていないのが、列(縦方向)をコントロールする「colgroup」タグ。また、colgroupタグはcaptionタグの次に、tfootタグはtbodyタグの前に記述、という「マークアップ順」。その他もろもろtableタグに関することをまとめておこうと思います。
テーブルを左から右へ情報を提供したいとき
表示例
見出し1 | データ1-1 | データ1-2 |
---|---|---|
見出し2 | データ2-2 | データ2-3 |
見出し3 | データ3-1 | データ3-2 |
見出し4 | データ4-1 | データ4-2 |
サンプルソース
<caption>テーブルの概要</caption>
<colgroup><col style="background-color:#ccc; width:140px;" /><col style="background-color:#eee; width:80px;" /><col style="background-color:#ccc; width:80px;" /></colgroup>
<tbody>
<tr>
<th scope="row">見出し1</td>
<td>データ1-1</td>
<td>データ1-2</td>
</tr>
<tr>
<th scope="row">見出し2</td>
<td>データ2-2</td>
<td>データ2-3</td>
</tr>
<tr>
<th scope="row">見出し3</td>
<td>データ3-1</td>
<td>データ3-2</td>
</tr>
<tr>
<th scope="row">見出し4</td>
<td>データ4-1</td>
<td>データ4-2</td>
</tr>
</tbody>
</table>
テーブルを上から下へ情報を提供したいとき
表示例
見出し1 | 見出し2 | 見出し3 |
---|---|---|
結果1 | 結果2 | 結果3 |
データ1-1 | データ2-1 | データ3-1 |
データ1-2 | データ2-2 | データ3-2 |
サンプルソース
<caption>テーブルの概要</caption>
<colgroup style="background-color:#ccc; width:100px;"></colgroup>
<colgroup style="background-color:#eee; width:100px;"></colgroup>
<colgroup style="background-color:#ccc; width:100px;"></colgroup>
<thead>
<tr>
<th scope="col">見出し1</th>
<th scope="col">見出し2</th>
<th scope="col">見出し3</th>
</tr>
</thead>
<tfoot>
<tr>
<td>結果1</td>
<td>結果2</td>
<td>結果3</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>データ1-1</td>
<td>データ2-1</td>
<td>データ3-1</td>
</tr>
<tr>
<td>データ1-2</td>
<td>データ2-2</td>
<td>データ3-2</td>
</tr>
</tbody>
</table>
tableタグの使いどころ
tableタグのマークアップ順
- table
- caption(任意)
- colgroup(任意)
- col(任意)
- thead(任意)
- tr
- th(任意)
- td
- tfoot(任意)
- tr
- th(任意)
- td
- tbody(任意)
- tr
- th(任意)
- td
- tableタグに「cellspacing=”0″」を記述
- レイアウト崩れが発生する可能性を排除するため
- tableタグに「border=”1″」を記述
- CSSが効いていない状態でも表として分かりやすくするため。枠線を非表示にしたい場合はCSSを利用
- tableタグのsummary属性にtableの概要を記述
- tableの概要を記述するcaptionタグとの違いは、captionに書かれた記述はブラウザに表示されるが、summaryで書かれた記述はブラウザに表示されない
- scope属性の設置
- 音声読み上げブラウザに配慮し、横方向に読ませたいときは「scope="row"」を、縦方向に読ませたいときは「scope=”col”」を記述(アクセシビリティの向上)
- 列(縦方向)をコントロールするcolgroupタグ
- 行(横方向)をコントロールするにはtrタグを使うが、列をコントロールする場合はcolgroupタグを使用する
colgroupの記述の仕方は2通りある(その違いは上記のサンプルソースを参照) - thead,tfoot,tbody
- thead,tfoot,tbodyを利用する際は、書き順に注意。ブラウザの表示されるのは、thead,tbody,tfootの順だが、マークアップはthead,tfoot,tbodyの順に記述する