HTMLでtableタグを用いた表にあるセルを結合する方法

ここではHTMLでtable内のセルを結合する方法について説明していきます。
この記事を読むことで、HTMLの属性や、rowspan属性やcolspan属性について理解し、その出力結果をオンラインエディターを用いて見ることができます。
table内のセルを結合するためには、thタグやtdタグにrowspan属性やcolspan属性を指定します。
HTMLにおける属性とは
HTMLにおける属性というのは、HTMLの各要素に付ける何かしらの設定のことです。
rowspan属性とは
rowspan属性とは、tableタグ内のセルを縦方向に結合する属性です。
colspan属性とは
colspan属性とは、tableタグ内のセルを横方向に結合する属性です。
コーディング例
・HTML
<div class="table-wrapper">
<table class="table-wrapper__table table">
<caption class="table__caption">
キャプション
</caption>
<thead class="table__thead thead">
<tr class="thead__tr">
<th scope="col" class="thead__th">テーブルヘッダー</th>
<th scope="col" class="thead__th">テーブルヘッダー</th>
<th scope="col" class="thead__th" colspan="2">テーブルヘッダー</th>
</tr>
</thead>
<tbody class="table__tbody tbody">
<tr class="tbody__tr">
<th scope="row" class="tbody__th">テーブルヘッダー</th>
<td scope="col" class="tbody__td">テーブルデータ</td>
<td scope="col" class="tbody__td" colspan="2">テーブルデータ(colspan="2")</td>
</tr>
<tr class="tbody__tr">
<th scope="row" class="tbody__th" rowspan="2">テーブルヘッダー</th>
<td scope="col" class="tbody__td" rowspan="2">テーブルデータ(rowspan="2")</td>
<td scope="col" class="tbody__td">テーブルデータ</td>
<td scope="col" class="tbody__td">テーブルデータ</td>
</tr>
<tr class="tbody__tr">
<td scope="col" class="tbody__td">テーブルデータ</td>
<td scope="col" class="tbody__td">テーブルデータ</td>
</tr>
</tbody>
</table>
</div>
<!-- /.table-wrapper -->
・CSS
.table-wrapper {
padding: 40px;
}
.table {
width: 100%;
max-width: 600px;
border-collapse: collapse;
}
.table__caption {
font-weight: 700;
margin-bottom: 5px;
}
.tbody {
border-left: 2px solid #000;
border-bottom: 2px solid #000;
border-right: 2px solid #000;
}
.tbody__th {
border-right: 2px solid #000;
border-bottom: 1px solid #000;
padding: 15px 10px;
text-align: center;
}
.tbody__td {
border-right: 2px solid #000;
border-bottom: 1px solid #000;
padding: 15px 10px;
text-align: center;
}
.thead {
border-left: 2px solid #000;
border-top: 2px solid #000;
border-right: 2px solid #000;
}
.thead__th {
border: 2px solid #000;
padding: 15px 10px;
text-align: center;
}
出力結果
See the Pen Untitled by Yagi-System (@ihspycal-the-lessful) on CodePen.
まとめ
上記のように、HTMLのtableタグにあるthタグやtdタグにrowspan属性やcolspan属性を指定することで、table内にあるセルを結合することができます。