首页 / HTML5 入门教程 / 表格可访问性

HTML5 入门教程

表格可访问性

本教程共 110 篇 · 第 49 篇 · 更新于 2026-07-28 · 约 6 分钟阅读

HTML5HTML5 入门教程可访问性a11yscopeheaders屏幕阅读器

49. 表格可访问性

本节目标:理解表格可访问性的重要性,学会用 scope 和 id/headers 属性让屏幕阅读器正确解读表格。

视力正常的用户可以一眼看出表格的结构。但屏幕阅读器用户需要代码告诉他们哪个是表头、哪个是数据、它们之间是什么关系。

scope 属性(简单表格)

scope 是设置可访问性最简单的方式。

<table>
  <tr>
    <th scope="col">姓名</th>
    <th scope="col">年龄</th>
  </tr>
  <tr>
    <th scope="row">张三</th>
    <td>28</td>
  </tr>
</table>

scope 的可选值:

含义
col该 th 是这一列的标题
row该 th 是这一行的标题
colgroup该 th 是多列分组的标题
rowgroup该 th 是多行分组的标题

colgroup 和 rowgroup

当表头有分组时,用这两个值:

<table>
  <thead>
    <tr>
      <th colspan="3" scope="colgroup">衣物</th>
    </tr>
    <tr>
      <th scope="col">长裤</th>
      <th scope="col">裙子</th>
      <th scope="col">衬衫</th>
    </tr>
  </thead>
</table>

“衣物”跨了 3 个子列,所以用 scope=“colgroup”。子列标题用 scope=“col”。

id 和 headers 属性(复杂表格)

对于更复杂的表格(多级表头、交叉表头),scope 不够用。这时用 id 和 headers 建立精确关联。

思路:

  1. 给每个 th 一个唯一的 id
  2. 在 td 上写 headers 属性,值是关联的 th 的 id 列表
<table>
  <thead>
    <tr>
      <th id="clothes" colspan="3">衣物</th>
    </tr>
    <tr>
      <th id="trousers" headers="clothes">长裤</th>
      <th id="skirts" headers="clothes">裙子</th>
      <th id="shirts" headers="clothes">衬衫</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="belgium">比利时</th>
      <th id="antwerp" headers="belgium">安特卫普</th>
      <td headers="antwerp belgium clothes trousers">56</td>
      <td headers="antwerp belgium clothes skirts">22</td>
      <td headers="antwerp belgium clothes shirts">43</td>
    </tr>
  </tbody>
</table>

每个 td 的 headers 列出了它关联的所有标题 id,像电子表格的行列坐标一样精确。

Note

id/headers 方法虽然精确,但代码量很大。大多数表格用 scope 就够了。

caption 的重要性

别忘了 caption。屏幕阅读器会先读出 caption,让用户知道这张表格是关于什么的,再决定要不要继续听详细内容。

<table>
  <caption>2024年8月销售数据(单位:件)</caption>
  <!-- 表格内容 -->
</table>

可访问性检查清单

  • 每个表格有 caption
  • 所有 th 都有 scope 属性(简单表格)
  • 复杂表头使用 id/headers
  • 不要用表格做页面布局
  • 确保表头和数据有逻辑关联

小结

  • scope 适合大多数表格(col、row、colgroup、rowgroup)
  • id/headers 适合复杂的多级表头
  • caption 帮助用户快速了解表格内容
  • 可访问性不是可选的,是基本要求

下一节,我们学习表格的响应式处理。