🏓

rowspanを使ってセルを垂直に結合する

2023/03/22に公開

やりたいこと

以下のように、セルを結合したテーブルを作りたい。

これはtd要素にrowspanを付与して上げればよい。(以下はJSXでベタ書きしています)

    <table className="table is-bordered is-hoverable"> 
      <thead>
        <tr>
          <th>カテゴリ</th>
          <th>Bad</th>
          <th>OK</th>
          <th>Good</th>
          <th>Great</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th rowSpan={2}>カテゴリ1</th>
          <th>サブカテゴリ1</th>
          <td><input type="radio"/></td>
          <td><input type="radio"/></td>
          <td><input type="radio"/></td>
        </tr>
        <tr>
          <th>サブカテゴリ2</th>
          <td><input type="radio"/></td>
          <td><input type="radio"/></td>
          <td><input type="radio"/></td>
        </tr>
      </tbody>
    </table>

className="table is-bordered is-hoverable"のクラスはBulma CSSによるもの。

rowspanとは:

この属性はセルをいくつの行に広げるかを示す、負でない整数を持ちます。既定値は 1 です。0 を設定した場合は、セルが属する表セクション (<thead>, <tbody>, <tfoot>) の終端 (暗黙的に定義されるものであっても) まで拡張します。65534 より大きな値は、65534 に切り詰めます。
<td>: 表データセル要素 - HTML: HyperText Markup Language | MDN

なお、水平方向に結合したい場合はcolspanが使える。
<td>: 表データセル要素 - HTML: HyperText Markup Language | MDN

rowspan,colspanはtd要素、th要素どちらにも使用できる。

今まであんまりテーブル書いたことないからいろいろ知れて良かった🙌

Discussion