萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML 表格標籤使用指南:語義化結構與無障礙最佳實踐

HTML 表格標籤完整使用指南:結構、語義與無障礙

正確使用表格標籤不僅關乎顯示,更影響螢幕閱讀器解讀、SEO 索引、列印佈局。本文系統梳理 10 大核心標籤與最佳實踐。

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 屬性:建立標題關聯(無障礙關鍵)

scope 值 適用位置 語義
col <th> 在 <thead> 此儲存格是欄標題
row <th> 在 <tbody> 首欄 此儲存格是列標題
colgroup <th colspan> 此儲存格是欄群組標題
rowgroup <th rowspan> 此儲存格是列群組標題

headers/id 進階關聯(複雜合併表格)

<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>

CSS 樣式最佳實踐

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;
}

何時不該用表格

  • ❌ 頁面佈局 → 用 Flexbox/Grid
  • ❌ 簡單鍵值對列表 → 用 <dl><dt><dd>
  • ❌ 純視覺網格 → 用 CSS Grid
  • ✅ 多維度關聯數據、財務報表、比較矩陣、時刻表

無障礙檢查清單

  • ✅ 有 <caption> 描述表格用途
  • ✅ <th> 正確使用 scope
  • ✅ 複雜合併用 headers/id 關聯
  • ✅ 色彩對比度達標(WCAG AA)
  • ✅ 鍵盤可導航(原生表格天然支援)
  • ✅ 響應式不破壞語義結構

語義化表格 = 更好的無障礙 + 更好的 SEO + 更易維護的代碼。

copyright © 萬盛學電腦網 all rights reserved