0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【HTML・CSS】表のセルを横方向に結合する方法

Last updated at Posted at 2023-11-03

背景

表としては1列で表示しつつも、一部の行では2列で表示させたい事があった。
表のセルを結合させるという発想がすぐに出てこず、1つのセルの中にもう1つセルを作れないか考えたが、思うようにはいかなかった。
本記事では、以下画像のような表のセル同士を結合させて一部の行だけ2列に表示させた方法について記載します。

  • 表のイメージ

image.png

全体のコード

以下が全体のコードを記載します。
今回は表の見出しとなる<th>タグは使用しておりません。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 表 -->
    <table border="1">
        <!-- 1行目 -->
        <tr>
            <td colspan="2">1st Column</td>
        </tr>
        <!-- 2行目 -->
        <tr>
            <td colspan="2">1st Column</td>
        </tr>
        <!-- 3行目 -->
        <tr>
            <td style="width: 75%;">1st Column</td>
            <td style="width: 25%;">2nd Column</td>
        </tr>
    </table>
</body>

</html>

コードの詳細

ポイントはCSSとして適用させているcolspan属性です。
colspan属性を使用する事でテーブルのセルを横方向に結合させる事ができます。
今回は表を2列で作成しており、1行目と2行目を横方向にセルを結合させています。

<!-- 表 -->
    <table border="1">
        <!-- 1行目 -->
        <tr>
            <td colspan="2">1st Column</td>
        </tr>
        <!-- 2行目 -->
        <tr>
            <td colspan="2">1st Column</td>
        </tr>
        <!-- 3行目 -->
        <tr>
            <td style="width: 75%;">1st Column</td>
            <td style="width: 25%;">2nd Column</td>
        </tr>
    </table>
  • colspan属性=結合するセルの数
    のため、今回は2つのセルを横方向に結合させています。
<td colspan="2">1st Column</td>

補足
今回は表のセルを横方向にcolspan属性で結合させましたが、
rowspan属性を使用すると縦方向にセルを結合します。

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?