语义化表格
语义化表格通过正确的标签结构,帮助屏幕阅读器和搜索引擎理解表格数据关系。
基本结构
HTML
<table>
<caption>2024年度销售报表</caption>
<thead>
<tr>
<th scope="col">月份</th>
<th scope="col">销售额</th>
<th scope="col">增长率</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">一月</th>
<td>¥120,000</td>
<td>5%</td>
</tr>
<tr>
<th scope="row">二月</th>
<td>¥135,000</td>
<td>12.5%</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">合计:¥255,000</td>
</tr>
</tfoot>
</table>
核心元素
| 元素 | 用途 |
|---|---|
<table> | 表格容器 |
<caption> | 表格标题/说明 |
<thead> | 表头区域 |
<tbody> | 表体区域 |
<tfoot> | 表尾区域 |
<tr> | 表格行 |
<th> | 表头单元格 |
<td> | 数据单元格 |
表头关联(scope)
scope 属性
HTML
<thead>
<tr>
<th scope="col">产品名称</th>
<th scope="col">单价</th>
<th scope="col">数量</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">iPhone 15</th>
<td>¥5999</td>
<td>50</td>
</tr>
</tbody>
| scope值 | 说明 |
|---|---|
| col | 列表头,关联整列数据 |
| row | 行表头,关联整行数据 |
| colgroup | 列组表头 |
| rowgroup | 行组表头 |
复杂表格结构
多级表头
HTML
<table>
<caption>学生成绩表</caption>
<thead>
<tr>
<th rowspan="2" scope="colgroup">学生</th>
<th colspan="3" scope="colgroup">考试成绩</th>
</tr>
<tr>
<th scope="col">语文</th>
<th scope="col">数学</th>
<th scope="col">英语</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">张三</th>
<td>85</td>
<td>92</td>
<td>88</td>
</tr>
</tbody>
</table>
id 与 headers 关联
HTML
<table>
<thead>
<tr>
<th id="name">姓名</th>
<th id="mon">周一</th>
<th id="tue">周二</th>
</tr>
</thead>
<tbody>
<tr>
<td headers="name">李四</td>
<td headers="mon">出勤</td>
<td headers="tue">请假</td>
</tr>
</tbody>
</table>
表格分组
tbody 多组
HTML
<table>
<thead>
<tr>
<th>部门</th>
<th>人数</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="rowgroup" colspan="2">技术部</th>
</tr>
<tr>
<td>前端组</td>
<td>15</td>
</tr>
<tr>
<td>后端组</td>
<td>20</td>
</tr>
</tbody>
<tbody>
<tr>
<th scope="rowgroup" colspan="2">市场部</th>
</tr>
<tr>
<td>销售组</td>
<td>30</td>
</tr>
</tbody>
</table>
无障碍增强
aria 属性
HTML
<table role="table" aria-describedby="table-desc">
<caption id="table-desc">
本表格展示2024年各部门预算分配情况
</caption>
<!-- 表格内容 -->
</table>
响应式表格
HTML
<div class="table-wrapper" role="region" aria-label="数据表格" tabindex="0">
<table>
<!-- 表格内容 -->
</table>
</div>
<style>
.table-wrapper {
overflow-x: auto;
max-width: 100%;
}
</style>
常见错误
| 错误做法 | 正确做法 |
|---|---|
用 <div> 模拟表格 | 使用 <table> |
缺少 <caption> | 添加表格标题 |
<td> 当表头 | 使用 <th> + scope |
跳过 <thead> | 结构完整分组 |
| 用表格做布局 | 仅用于数据展示 |
注意:表格仅用于展示数据表格,不应用于页面布局。
要点总结
<caption>提供表格标题,屏幕阅读器会首先朗读<thead>、<tbody>、<tfoot>划分表格区域<th scope="col/row">关联表头与数据- 复杂表格使用
headers属性精确关联 - 响应式表格需添加横向滚动容器
📝 发现内容有误?点击此处直接编辑