正確使用表格標籤不僅關乎顯示,更影響螢幕閱讀器解讀、SEO 索引、列印佈局。本文系統梳理 10 大核心標籤與最佳實踐。
| 標籤 | 語義 | 必要性 | 父容器 | 關鍵屬性 |
|---|---|---|---|---|
<table> |
表格根容器 | 必填 | 任意 | — |
<caption> |
表格標題/摘要 | 強烈建議 | table (首個子元素) | — |
<colgroup> |
欄群組 | 選填 | table (caption 後) | span |
<col> |
單欄定義 | 選填 | colgroup | span, style |
<thead> |
表頭區塊 | 建議 | table | — |
<tbody> |
主體區塊 | 隱含必要 | table | — |
<tfoot> |
底部/摘要區 | 選填 | table (thead 後) | — |
<tr> |
列 | 必填 | thead/tbody/tfoot | — |
<th> |
標題儲存格 | 表頭必填 | tr (thead) | scope, colspan, rowspan |
<td> |
資料儲存格 | 主體必填 | tr (tbody/tfoot) | colspan, rowspan, headers |
<table>
<caption>2024 年各季產品營收統計(單位:萬元)</caption>
<colgroup>
<col span="1" style="width: 120px;">
<col span="3" style="width: 100px;">
<col style="width: 100px;">
</colgroup>
<thead>
<tr>
<th scope="col">產品</th>
<th scope="col">Q1</th>
<th scope="col">Q2</th>
<th scope="col">Q3</th>
<th scope="col">Q4</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">產品 A</th>
<td>120</td><td>135</td><td>142</td><td>158</td>
</tr>
<tr>
<th scope="row">產品 B</th>
<td>95</td><td>102</td><td>110</td><td>125</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">總計</th>
<td>215</td><td>237</td><td>252</td><td>283</td>
</tr>
</tfoot>
</table>
| scope 值 | 適用位置 | 語義 |
|---|---|---|
col |
<th> 在 <thead> |
此儲存格是欄標題 |
row |
<th> 在 <tbody> 首欄 |
此儲存格是列標題 |
colgroup |
<th colspan> |
此儲存格是欄群組標題 |
rowgroup |
<th rowspan> |
此儲存格是列群組標題 |
<table>
<tr>
<th id="p">產品</th>
<th id="q1">Q1</th>
<th id="q2">Q2</th>
</tr>
<tr>
<th headers="p" id="prodA">產品 A</th>
<td headers="q1 prodA">120</td>
<td headers="q2 prodA">135</td>
</tr>
</table>
table {
border-collapse: collapse;
width: 100%;
font-variant-numeric: tabular-nums; /* 數字等寬對齊 */
}
th, td {
padding: 12px 16px;
border: 1px solid #e0e0e0;
text-align: left;
}
thead th {
background: #f5f5f5;
font-weight: 600;
position: sticky;
top: 0; /* 滾動時表頭固定 */
z-index: 1;
}
tbody tr:nth-child(even) { background: #fafafa; }
tbody tr:hover { background: #e8f4fd; }
tfoot th, tfoot td {
background: #f0f0f0;
font-weight: 600;
}
caption {
caption-side: top;
padding: 12px;
font-weight: 600;
font-size: 1.1em;
}
<dl><dt><dd><caption> 描述表格用途<th> 正確使用 scopeheaders/id 關聯語義化表格 = 更好的無障礙 + 更好的 SEO + 更易維護的代碼。