thタグ -table内でヘッダーセルを作成する|HTML辞典
<th>タグとは?
<th>
タグは、HTML の <table>
(表)内でヘッダーセル(見出しセル)を作成するためのタグです。
デフォルトで太字+中央寄せのスタイルが適用され、列や行のタイトルを明示する際に使用されます。
基本情報
コンテンツモデル
フローコンテンツ(Flow Content)。
閉じタグの有無
<th>
は 開始タグ(<th>
)と閉じタグ(</th>
)の両方が必要 です。
基本的な記述方法
<table>
<tr>
<th>商品名</th>
<th>価格</th>
</tr>
<tr>
<td>りんご</td>
<td>100円</td>
</tr>
<tr>
<td>バナナ</td>
<td>150円</td>
</tr>
</table>
この記述により、1 行目のセルがヘッダーセル(太字・中央寄せ)になります。
使用できる主な属性
属性名 | 説明 | 例 |
---|---|---|
colspan | セルを 横方向に結合 | <th colspan="2"> |
rowspan | セルを 縦方向に結合 | <th rowspan="3"> |
scope | ヘッダーの適用範囲を指定 | <th scope="col"> |
abbr | ヘッダーの省略形を指定 | <th abbr="価格">値段</th> |
scope
の使用例
<table>
<tr>
<th scope="col">商品</th>
<th scope="col">価格</th>
</tr>
<tr>
<td>りんご</td>
<td>100円</td>
</tr>
</table>
scope="col"
を指定することで、列の見出しであることを明確にしています。
colspan
の使用例
<table>
<tr>
<th colspan="2">商品情報</th>
</tr>
<tr>
<td>バナナ</td>
<td>150円</td>
</tr>
</table>
「商品情報」のセルが 2 列分結合されています。
CSSを使ったデザイン変更
<th>
のデフォルトのスタイルは 太字+中央寄せ ですが、CSS で変更可能です。
th {
background-color: #f2f2f2;
padding: 10px;
border: 1px solid #ccc;
text-align: left;
}
適切な使用例
テーブルのヘッダーセルを作成する
<table>
<tr>
<th>商品</th>
<th>価格</th>
</tr>
<tr>
<td>みかん</td>
<td>200円</td>
</tr>
</table>
colspan
でセルを横方向に結合する
<table>
<tr>
<th colspan="2">商品情報</th>
</tr>
<tr>
<td>バナナ</td>
<td>150円</td>
</tr>
</table>
rowspan
でセルを縦方向に結合する
<table>
<tr>
<th rowspan="2">商品</th>
<th>価格</th>
</tr>
<tr>
<th>税込価格</th>
</tr>
<tr>
<td>りんご</td>
<td>100円</td>
</tr>
</table>
適切でない使用例(誤った使い方)
<th>
を <table>
の外に記述する
<!-- NG: <table> の外に <th> を記述 -->
<th>商品名</th>
<table>
<tr>
<td>りんご</td>
</tr>
</table>
正しい書き方(
<table>
内に記述)
<table>
<tr>
<th>商品名</th>
</tr>
</table>
scope
の指定が不適切
<!-- NG: 不適切な `scope` の指定 -->
<table>
<tr>
<th scope="row">商品</th>
<th scope="col">価格</th>
</tr>
<tr>
<td>りんご</td>
<td>100円</td>
</tr>
</table>
正しい書き方(
scope
の適用範囲を正確に指定)
<table>
<tr>
<th scope="col">商品</th>
<th scope="col">価格</th>
</tr>
</table>
<th>タグと他のタグの違い
タグ | 役割 | 特徴 | 適切な用途 |
---|---|---|---|
<th> | ヘッダーセルを作成する | デフォルトで太字+中央寄せ | 列名やカテゴリー名 |
<td> | データセルを作成する | 通常のデータ用 | 数値やテキストの表示 |
<tr> | 行を作成する | <th> や <td> を内包 | 表の行 |
<thead> | ヘッダーをグループ化 | <tr> を含む | 表の見出し行 |
<tbody> | データ部分をグループ化 | <tr> を含む | メインのデータ行 |
<tfoot> | フッターをグループ化 | <tr> を含む | 合計や備考などの行 |
使用上の注意点
<th>
はヘッダーセルとして使用する
- データセルには
<td>
を使用し、タイトル部分のみ<th>
にする。
scope
を適切に設定すると、アクセシビリティが向上
scope="col"
(列のヘッダー)、scope="row"
(行のヘッダー)を適切に使用。
colspan
や rowspan
を活用して、より分かりやすい表を作成する
- ただし、適用ミスに注意する。
関連タグ
<table>
– 表を作成<caption>
– 表のタイトルを指定<tr>
– 行を作成<td>
– データセルを作成<thead>
– ヘッダー部分をグループ化<tbody>
– データ部分をグループ化<tfoot>
– フッター部分をグループ化
まとめ
<th>
タグは、HTML の 表のヘッダーセルを作成するためのタグ です。
適切に使用することで、データの可読性が向上し、アクセシビリティや SEO にも貢献します。