首页 > 解决方案 > HTML表格:合并行单元格

问题描述

我有以下代码:

<div style="text-align: center; color: #345; padding-top: 10px;">
  <table style="border-collapse: collapse; width: 100%; height: 270px;" border="1">
    <tbody>
      <tr style="height: 126px;">
        <td style="width: 50%; height: 126px;"><strong>abc</strong></td>
        <td style="width: 50%; height: 126px;"><strong>abc</strong></td>
      </tr>
      <tr style="height: 18px;">
        <td style="width: 50%; height: 18px;">x</td>
        <td style="width: 50%; height: 18px;">y</td>
      </tr>
      <tr style="height: 108px;">
        <td style="width: 50%; height: 108px;"><strong>abc</strong></td>
        <td style="width: 50%; height: 108px;"><strong>abc</strong></td>
      </tr>
      <tr style="height: 18px;">
        <td style="width: 50%; height: 18px;">x</td>
        <td style="width: 50%; height: 18px;">y</td>
      </tr>
    </tbody>
  </table>
  <p>&nbsp;</p>
</div>

生成下表:

在此处输入图像描述

如何合并我的“x”和“y”单元格,以便它们所在的行仅包含一个单元格“xy”?

标签: html

解决方案


<table style="border-collapse: collapse; width: 100%; height: 270px;" border="1">
    <tbody>
    <tr style="height: 126px;">
        <td style="width: 50%; height: 126px;"><strong>abc</strong></td>
        <td style="width: 50%; height: 126px;"><strong>abc</strong></td>
    </tr>
    <tr style="height: 18px;">
        <td style="height: 18px;" colspan="2">xy</td>
    </tr>
    <tr style="height: 108px;">
        <td style="width: 50%; height: 108px;"><strong>abc</strong></td>
        <td style="width: 50%; height: 108px;"><strong>abc</strong></td>
    </tr>
    <tr style="height: 18px;">
        <td style="height: 18px;" colspan="2">xy</td>
    </tr>
    </tbody>
</table>

Colspan 是您所寻求的。也不知道是否有人告诉你,但内联 CSS 是不好的做法,你应该改用 class

在这里,您有带有类而不是内联 css 的代码:(结果相同但更漂亮)

.bigRow {
        height: 126px;
    }
    
    .bigRow-2 {
        height: 108px;
    }

    .bigRow td, .bigRow-2 td {
        height: 100%;
        width: 50%;
    }

    .smallRow {
        height: 18px;
    }
<div style="text-align: center; color: #345; padding-top: 10px;">
    <table style="border-collapse: collapse; width: 100%; height: 270px;" border="1">
        <tbody>
        <tr class="bigRow">
            <td><strong>abc</strong></td>
            <td><strong>abc</strong></td>
        </tr>
        <tr class="smallRow">
            <td colspan="2">xy</td>
        </tr>
        <tr class="bigRow-2">
            <td><strong>abc</strong></td>
            <td><strong>abc</strong></td>
        </tr>
        <tr class="smallRow">
            <td colspan="2">xy</td>
        </tr>
        </tbody>
    </table>
    <p>&nbsp;</p>
</div>


推荐阅读