You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML表格<tr>元素未正常换行的问题咨询

HTML表格元素未正常换行的问题咨询

嘿,我最近写了一个两列的HTML表格,用了Bootstrap的表格样式,本来以为是个简单的需求,结果发现元素没法正常换行,布局看起来怪怪的。我写的代码如下:

<table class="table table-striped table-bordered">
   <thead>
      <tr>
        <th></th>
        <th>Fans</th>
      </tr>
   </thead>
   <tbody>
      <tr>
        <td rowspan="2">
          Supply air
        </td>
        <td rowspan="2">
        {#if Object.entries(supply_air_fan).length}
          {supply_air_fan.name}<br>{supply_air_fan.value}
        {/if}
        </td>
      </tr>
      <tr>
        <td rowspan="2">
          Exhaust air
        </td>
        <td rowspan="2">
        {#if Object.entries(exhaust_air_fan).length}
          {exhaust_air_fan.name}<br>{exhaust_air_fan.value}
        {/if}
        </td>
      </tr>
   </tbody>
</table>

我现在的问题是,表格里的没有按照预期换行,布局结构混乱。后来仔细捋了捋,应该是我对rowspan属性的用法搞错了:

  • 我给第一个里的两个都加了rowspan="2",这意味着这两个单元格会合并两行的位置,占据两行的高度。但紧接着我又写了一个完整的,里面同样加了rowspan="2"的,这就导致浏览器解析表格结构时出现冲突,没法正确识别行的换行逻辑。

如果我的需求是让“Supply air”和“Exhaust air”这两个类别各占一行(或者希望单元格有一定高度),其实不需要用rowspan,改用CSS来设置单元格的内边距或者高度就可以了。如果确实需要合并多行单元格(比如同一列有多个重复内容),那正确的结构应该是这样的:

<table class="table table-striped table-bordered">
   <thead>
      <tr>
        <th></th>
        <th>Fans</th>
      </tr>
   </thead>
   <tbody>
      <!-- Supply air 占两行,对应两个Fans内容 -->
      <tr>
        <td rowspan="2">Supply air</td>
        <td>
          {#if Object.entries(supply_air_fan1).length}
            {supply_air_fan1.name}<br>{supply_air_fan1.value}
          {/if}
        </td>
      </tr>
      <tr>
        <td>
          {#if Object.entries(supply_air_fan2).length}
            {supply_air_fan2.name}<br>{supply_air_fan2.value}
          {/if}
        </td>
      </tr>
      <!-- Exhaust air 占两行,对应两个Fans内容 -->
      <tr>
        <td rowspan="2">Exhaust air</td>
        <td>
          {#if Object.entries(exhaust_air_fan1).length}
            {exhaust_air_fan1.name}<br>{exhaust_air_fan1.value}
          {/if}
        </td>
      </tr>
      <tr>
        <td>
          {#if Object.entries(exhaust_air_fan2).length}
            {exhaust_air_fan2.name}<br>{exhaust_air_fan2.value}
          {/if}
        </td>
      </tr>
   </tbody>
</table>

如果只是想让每个类别的单元格看起来更高一些,直接用CSS调整样式就行,比如:

.table tbody td {
  padding: 1.5rem 0.75rem; /* 增大内边距来增加高度 */
  /* 或者直接设置高度 */
  /* height: 80px; */
}

这样表格的就能正常换行了,布局也不会乱。

备注:内容来源于stack exchange,提问作者minisaurus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.16 08:14:36