LoginSignup
3
1

More than 1 year has passed since last update.

テーブルヘッダを結合させたいとき

Last updated at Posted at 2022-12-21

背景

スクリーンショット 2022-12-20 11.24.15.png

こんな感じの表をHTMLで実装したいとします。
ポイントは結合しているヘッダです。
果たしてどうやって実装するのでしょうか?

実装

<table>
  <col>
  <colgroup span="2"></colgroup>
  <colgroup span="2"></colgroup>
  <thead>
    <tr>
      <td rowspan="2"></td>
      <th colspan="2" scope="colgroup">Mars</th>
      <th colspan="2" scope="colgroup">Venus</th>
    </tr>
    <tr>
      <th scope="col">Produced</th>
      <th scope="col">Sold</th>
      <th scope="col">Produced</th>
      <th scope="col">Sold</th>
    </tr>
  </thead>
  <tbody>
    ~~~
  </tbody>
</table>

こうなります。
<colgroup>とか<th colspan>とか、生でテーブル実装していない方だと
見慣れないものかもしれません。
実際私も見慣れないものでした。

colgroup

<colgroup>とは、列のグループを定義するものです。

<colgroup><table>の子要素として配置され、
かつ<thead>の前に置かれます。

<table>
    <colgroup span="2">
    <thead></thead>
    <tbody></tbody>
</table>

そして、span属性により<colgroup>要素がまたがる列の数を示します。
上記の例であれば、2列にまたがるグループを定義しているということです。

th colspan

<th>は表の見出しセルを定義します。
そして、<th>に指定するcolspanセルを幾つの列に広げるかを示します。

<table>
    <colgroup span="2">
    <colgroup span="2">
    <thead>
        <tr>
            <th colspan="2" scope="colgroup">hoge</th>
            <th colspan="2" scope="colgroup">fuga</th>
        </tr>
        <tr>
            <th scope="col">hoge 1</th>
            <th scope="col">hoge 2</th>
            <th scope="col">fuga 1</th>
            <th scope="col">fuga 2</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

そしてscope属性によって見出し要素が関連するセルを定義しておきます。
この場合は先に定義したcolgroupを指定することで、
この見出しが列グループに属し、その中の全てのセルに関連することを定義します。

グループ化したヘッダカラムの中に属する2段目ヘッダカラムにはscope="col"を指定することで、
グループ化したヘッダカラムの列に属する全てのセルに関連することを定義しています。

参考

Tables with Irregular Headers
colgroup: 表の列グループ要素
th: 表見出し要素

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1