0%

表格

表格(HTML Tables)

目录

  • 表格基础结构
  • 表头关联与语义
  • 合并单元格
  • 辅助元素与可访问性
  • 布局与样式要点
  • 响应式与滚动策略
  • 性能与实践建议

表格基础结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<table>
<caption>年度销售数据</caption>
<thead>
<tr>
<th scope="col">季度</th>
<th scope="col">销售额</th>
<th scope="col">同比</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Q1</th>
<td>120w</td>
<td>+8%</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">合计</th>
<td colspan="2">480w</td>
</tr>
</tfoot>
</table>
  • table:表格容器。
  • thead / tbody / tfoot:头、体、脚分区,便于样式与数据操作。
  • tr 行、th 表头单元、td 普通单元。

表头关联与语义

  • scope:用于 th,声明表头作用范围。
    • scope="col" 列表头;scope="row" 行表头。
    • 复杂表头(多级行/列)可用 colgroup/rowgroup
  • headers + id:当表格有跨行/跨列复杂表头时,用 th idtd headers 精确关联,辅助屏幕阅读器。
  • 多级表头示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <thead>
    <tr>
    <th rowspan="2" scope="col">产品</th>
    <th colspan="2" scope="colgroup">营收</th>
    </tr>
    <tr>
    <th scope="col">国内</th>
    <th scope="col">海外</th>
    </tr>
    </thead>

合并单元格

  • rowspan:跨行;colspan:跨列。
  • 注意:合并后需保证总列数一致,否则布局可能错乱。
    1
    2
    3
    <td rowspan="2">华东</td>
    <td>上海</td>
    <td>120</td>

辅助元素与可访问性

  • caption:表格标题,默认居上;可用 CSS 调整位置。
  • 摘要/说明:已废弃 summary 属性,推荐用:
    • 邻近文本说明(如 <p>),并用 aria-describedby 关联;
    • 或在 caption 内追加简要描述。
  • 表格分组:colgroup / col 可对列统一设置宽度/样式。
  • 无障碍要点:
    • 表头使用 th,并正确设置 scope
    • 为复杂表头提供 headers + id
    • 控制对比度、聚焦态,避免仅靠颜色区分。

布局与样式要点

  • 边框合并:table { border-collapse: collapse; }
  • 宽度与自适应:
    • table-layout: auto(默认):根据内容自动计算列宽。
    • table-layout: fixed:先看表格宽度再分配列宽,提升性能,长文本需 text-overflow 处理。
  • 行列样式:
    • :nth-child(even/odd) 斑马纹。
    • th 默认加粗居中,可按需重置。
  • 文本溢出处理:
    1
    2
    table { table-layout: fixed; width: 100%; }
    td, th { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

响应式与滚动策略

  • 外层水平滚动容器:
    1
    2
    3
    <div style="overflow-x:auto;">
    <table>...</table>
    </div>
  • 小屏折叠/堆叠:移动端可用 CSS/JS 将列转为卡片式列表(需额外标注表头信息)。
  • 优先展示关键列,隐藏次要列(display: none 或切换视图)。

性能与实践建议

  • 大数据表:
    • 优先分页/虚拟滚动,减少 DOM 行数。
    • 使用 table-layout: fixed 提升计算性能。
  • 可编辑表格:保持 th 语义,编辑控件放在 td 内;提交前同步数据。
  • 打印友好:为打印介质设置样式,隐藏无关操作列,保证表头重复显示(部分浏览器默认处理)。