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

如何阻止表格行高占满tbody,设置行高为tbody的10%

解决表格tbody中行高固定为10%的问题

默认表格布局下,直接给tr设置height:10%不会生效,因为表格会自动根据内容调整行高。要实现每行占tbody高度10%的效果,需要调整表格的布局模式,具体修改如下:

修改后的CSS代码

#home-index {
  margin-top: 10px;
}

table {
  table-layout: fixed;
  width: 100%;
  border-collapse: collapse;
}

thead, tfoot {
  display: block;
  width: 100%;
}

tbody {
  display: block;
  height: 604px;
  /* 如果需要超过10行后滚动,可添加下面一行 */
  /* overflow-y: auto; */
}

tr {
  display: table-row;
  height: 10%;
}

/* 固定列宽,适配fixed布局 */
th:nth-child(1), td:nth-child(1),
th:nth-child(2), td:nth-child(2) {
  width: 25%;
}

th:nth-child(n+3), td:nth-child(n+3) {
  width: 12.5%;
}

td {
  border: 1px solid lightgray;
  height: 100%;
}

.hours-cell:hover {
  background-color: darkorange;
}

th {
  border: 1px solid lightgray;
}

.dropdown {
  width: 100%;
}

关键修改说明

  1. 表格布局设置:给table添加table-layout: fixed和width:100%,固定表格布局,避免列宽随内容变化。
  2. 块级容器转换:将thead、tbody、tfoot设为display:block,让它们成为独立的块级容器,这样tbody的固定高度可以作为tr百分比高度的计算基准。
  3. 行高与列宽设置:给tr设置height:10%,让每行占tbody高度的1/10;同时给各列设置固定宽度,保证表格结构整齐。
  4. 单元格填充:给td设置height:100%,确保单元格内容填满行高,避免出现空白区域。

修改后的HTML代码(无需核心改动)

<table>
  <thead>
    <tr>
      <th>Project</th>
      <th>Task</th>
      <th>7/11</th>
      <th>7/12</th>
      <th>7/13</th>
      <th>Total Hours</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="dropdown">
        <select asp-for="Project" asp-items="Model.Projects"></select>
      </td>
      <td class="dropdown">
        <select asp-for="Task"></select>
      </td>
      <td class="hours-cell">--</td>
      <td class="hours-cell">--</td>
      <td class="hours-cell">--</td>
      <td></td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="2">Overall Totals</td>
      <td class="hours-cell">--</td>
      <td class="hours-cell">--</td>
      <td class="hours-cell">--</td>
      <td></td>
    </tr>
    <tr>
      <td colspan="2">Over/Under</td>
      <td class="hours-cell">--</td>
      <td class="hours-cell">--</td>
      <td class="hours-cell">--</td>
      <td></td>
    </tr>
  </tfoot>
</table>

添加行时,新行会自动排列在下方,直到填满10行(占满tbody高度)。如果需要支持超过10行的情况,给tbody添加overflow-y: auto即可实现垂直滚动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:45:34