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

如何用HTML colspan/rowspan实现首列分4格次列1格的表格并调宽?

解决方案

正确的表格HTML结构

你之前的问题出在colspan的使用对象错误(tr标签不能用colspan,只有td/th可以),以及没有正确匹配表头和下方单元格的数量对应关系。以下是符合需求的结构:

<table border="1">
  <thead>
    <tr>
      <!-- 首列表头跨4个单元格,对应下方每行的4个单元格 -->
      <th colspan="4">Performance Rating for last two years</th>
      <th>Disciplinary letters (in last two years)</th>
    </tr>
    <!-- 可添加二级表头明确评分维度 -->
    <tr>
      <th>Year</th>
      <th>Q1 Rating</th>
      <th>Q2 Rating</th>
      <th>Annual Rating</th>
      <th>Record</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>2023</td>
      <td></td>
      <td></td>
      <td></td>
      <!-- 右侧单元格跨2行,对应两行年份数据 -->
      <td rowspan="2"></td>
    </tr>
    <tr>
      <td>2022</td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

调整单元格宽度的CSS方法

要增大「Year」旁的单元格宽度,直接通过CSS精准定位目标单元格设置宽度即可:

/* 统一表格样式,避免边框重叠 */
table {
  border-collapse: collapse;
  width: 100%; /* 可选,让表格占满容器宽度 */
}

th, td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}

/* 给Year旁边的评分单元格设置宽度 */
tbody td:nth-child(2),
tbody td:nth-child(3),
tbody td:nth-child(4),
thead th:nth-child(2),
thead th:nth-child(3),
thead th:nth-child(4) {
  width: 20%; /* 根据需求调整数值 */
}

/* 也可以给Year列设置固定宽度,剩余空间分配给其他列 */
thead th:first-child,
tbody td:first-child {
  width: 15%;
}

关键说明

  • colspan="4":确保首列表头能覆盖下方的4个数据单元格,完全匹配需求;
  • rowspan="2":让右侧的纪律信件单元格同时对应两行年份数据,避免重复创建单元格;
  • CSS宽度设置:用nth-child选择器精准定位目标单元格,也可以给单元格添加类名来设置宽度,灵活度更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 23:30:57