【HTML】tableタグ - 表(テーブル)
HTMLのtableタグをご紹介します。
tableタグ
tableタグは表(テーブル)コンテンツをマークアップします。
基本構文
<table>
<thead>
<tr>
<th>列名</th>
<th>列名</th>
<th>列名</th>
</tr>
</thead>
<tbody>
<tr>
<th>行名</th>
<td>コンテンツ</td>
<td>コンテンツ</td>
</tr>
<tr>
<th>行名</th>
<td>コンテンツ</td>
<td>コンテンツ</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>行名</th>
<td>コンテンツ</td>
<td>コンテンツ</td>
</tr>
</tfoot>
</table>
tableタグは表に関するいくつかのタグと合わせて使用します。
thead
theadタグは行見出しグループをマークアップします。
tbody
tbodyタグは内容グループをマークアップします。
tfoot
tfootタグは行総括グループをマークアップします。
tr
trタグは行をマークアップします。
th
thタグはセルの見出しをマークアップします。
td
tdタグはセルの内容をマークアップします。
なお、様々な表に関するタグがありますが、ブラウザではtr要素,td要素のみでも表として認識されます。
属性
主な属性をご紹介します。
属性名 | 必須 | 内容 |
---|---|---|
scope | - | 見出しの対象。
th要素に設定します。 row : 行 col : 列 rowgroup : 行グループ(thead,tbody,tfoot) colgroup : 列グループ(thead,tbody,tfoot) |
rowspan | - | セルの結合(列方向) |
colspan | - | セルの結合(行方向) |
サンプルコード
表のデフォルトでは枠線がない場合があります。
サンプルでは分かりやすくするため、枠線を付けるスタイル(装飾)のコードを掲載しています。
<style>
table { border-collapse: collapse; }
td,th { border: 1px solid black; }
</style>
表
<style>
table { border-collapse: collapse ; }
td,th { border: 1px solid black; }
</style>
<table>
<thead>
<tr>
<th>ページ</th>
<th>ユーザー数</th>
<th>アクセス数</th>
</tr>
</thead>
<tbody>
<tr>
<th>AAA</th>
<td>10</td>
<td>70</td>
</tr>
<tr>
<th>BBB</th>
<td>30</td>
<td>50</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>合計</th>
<td>40</td>
<td>120</td>
</tr>
</tfoot>
</table>
セルの結合(行方向)
<style>
table { border-collapse: collapse ; }
td,th { border: 1px solid black; }
</style>
<table>
<thead>
<tr>
<th>ページ</th>
<th>ユーザー数</th>
<th>アクセス数</th>
</tr>
</thead>
<tbody>
<tr>
<th>AAA</th>
<td>10</td>
<td>70</td>
</tr>
<tr>
<th>BBB</th>
<td colspan="2">未計測</td>
</tr>
</tbody>
</table>
セルの結合(列方向)
<style>
table { border-collapse: collapse ; }
td,th { border: 1px solid black; }
</style>
<table>
<thead>
<tr>
<th>カテゴリ</th>
<th>ページ</th>
<th>ユーザー数</th>
<th>アクセス数</th>
</tr>
</thead>
<tbody>
<tr>
<th rowspan="2">XXX</th>
<th>AAA</th>
<td>10</td>
<td>70</td>
</tr>
<tr>
<th>BBB</th>
<td>30</td>
<td>50</td>
</tr>
</tbody>
</table>
scope
<style>
table { border-collapse: collapse ; }
td,th { border: 1px solid black; }
</style>
<table>
<thead>
<tr>
<th scope="col">ページ</th>
<th scope="col">ユーザー数</th>
<th scope="col">アクセス数</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">AAA</th>
<td>10</td>
<td>70</td>
</tr>
<tr>
<th scope="row">BBB</th>
<td>30</td>
<td>50</td>
</tr>
</tbody>
</table>