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

嵌套表格场景下移除border-spacing间隙的技术求助

解决嵌套表格父行与子表格的间隙问题

我想要实现一个可包含子行的表格,普通行的间距完全符合需求,但当表格存在嵌套子表格时,不希望父行与嵌套表格之间存在间隙。

示例效果:
普通行间距正常的表格
存在嵌套表格间隙的表格

问题根源

当前代码通过border-spacing: 0 10px实现了普通行的间距,但这个样式会继承给嵌套的子表格,同时包含子表格的父单元格默认有上下padding,两者共同导致了不必要的间隙。

解决方案

通过以下两步调整即可解决:

  1. 移除包含嵌套表格的父单元格上下内边距
  2. 给嵌套表格取消行间距,并调整圆角样式避免冲突

修改后的完整代码

CSS

body{
  background:salmon
}

table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 10px;
}

thead {
  height: 60px;
}

th {
  background-color: #eee;
  color: #000;
  font-weight: 700;
  text-align: left;
  padding: 10px;
}

th:first-child,
tr:first-child td:first-child,
tr:first-child th:first-child {
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}

th:last-child,
tr:last-child td:last-child,
tr:last-child th:last-child,
tbody tr td:last-child {
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}

tbody tr {
  cursor: pointer;
}

tbody td {
  background-color: white;
  text-align: left;
  padding: 10px;
}

tbody tr td:first-child {
  border-bottom-left-radius: 5px;
  border-top-left-radius: 5px;
}

/* 移除嵌套表格父单元格的上下内边距 */
.has-nested-table td {
  padding-top: 0;
  padding-bottom: 0;
}

/* 嵌套表格专属样式 */
.nested-table {
  border-spacing: 0; /* 取消子表格行间距 */
}

.nested-table thead th {
  border-radius: 0; /* 子表格表头取消圆角,避免和父行冲突 */
}

.nested-table tbody tr:last-child td {
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px; /* 子表格最后一行设置底部圆角,和父行视觉统一 */
}

HTML

<table>
<tbody>
  <tr>
    <td>Data 1, Row 1</td>
    <td>Data 2, Row 1</td>
    <td>Data 3, Row 1</td>
  </tr>
  <tr class="has-nested-table">
    <td colspan="3">
      <!-- Nested Table -->
      <table class="nested-table">
        <thead>
          <tr>
            <th>Header subrow 1</th>
            <th>Header subrow 2</th>
            <th>Header subrow 3</th>
          </tr>
        </thead>
        <tr>
          <td>Cell 1</td>
          <td>Cell 2</td>
          <td>Cell 3</td>
        </tr>
      </table>
    </td>
  </tr>
  <tr>
    <td>Data 1, Row 2</td>
    <td>Data 2, Row 2</td>
    <td>Data 3, Row 2</td>
  </tr>
</tbody>
</table>

效果说明

  • 普通行之间保持原有的10px间距,符合需求
  • 嵌套表格和父行完全无缝衔接,没有多余间隙
  • 子表格的圆角样式和父行统一,视觉更协调

内容的提问来源于stack exchange,提问作者Sadeghbayan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:44:58