萬盛學電腦網

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

HTML 表格完整教程:從基礎結構到無障礙最佳實踐

表格的正確用途

表格僅用於展示表格化數據(二維數據矩陣),絕不可用於頁面佈局。語義正確的表格結構,配合 CSS 樣式,能提供優秀的可讀性、可排序性與無障礙訪問體驗。

基礎表格結構

<table>
  <caption>2024 年 Q1 季度銷售報表</caption>
  <thead>
    <tr>
      <th scope="col">產品</th>
      <th scope="col">1 月</th>
      <th scope="col">2 月</th>
      <th scope="col">3 月</th>
      <th scope="col">小計</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">產品 A</th>
      <td>1,200</td>
      <td>1,350</td>
      <td>1,100</td>
      <td>3,650</td>
    </tr>
    <tr>
      <th scope="row">產品 B</th>
      <td>980</td>
      <td>1,020</td>
      <td>1,150</td>
      <td>3,150</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th scope="row">總計</th>
      <td>2,180</td>
      <td>2,370</td>
      <td>2,250</td>
      <td>6,800</td>
    </tr>
  </tfoot>
</table>

核心標籤與屬性解析

標籤/屬性說明關鍵點
<caption>表格標題/說明放在 <table> 直後,無障礙必備
<thead>/<tbody>/<tfoot>行分組語義分組,支持獨立滾動、打印分頁
<th>表頭單元格必加 scope="col|row|colgroup|rowgroup"
<td>數據單元格可用 headers 屬性關聯多個表頭
colspan/rowspan跨列/跨行合併合併時注意無障礙 headers 關聯
<colgroup>/<col>列組/列定義可為整列統一設置寬度、樣式

無障礙(a11y)關鍵實踐

  1. Caption 必須有:屏幕閱讀器首先讀取 caption 理解表格主題
  2. th 必須有 scope:scope="col"(列頭)、scope="row"(行頭)
  3. 複雜表頭用 headers/id:多級表頭時,<th id="p1"> + <td headers="p1 q1">
  4. 數據單元格語義化:金額用 <data value="1200">1,200</data>,時間用 <time>
  5. 響應式策略:窄屏下 table { display: block; overflow-x: auto; } 或重構為卡片列表

CSS 樣式最佳實踐

table {
  border-collapse: collapse;  /* 合併邊框,避免雙線 */
  width: 100%;
  font-variant-numeric: tabular-nums; /* 數字等寬對齊 */
}
th, td {
  border: 1px solid #ddd;
  padding: 0.75rem 1rem;
  text-align: left;
}
thead th {
  background: #f8f9fa;
  font-weight: 600;
  position: sticky; top: 0;  /* 長表格固定表頭 */
  z-index: 1;
}
tbody tr:nth-child(even) { background: #fafafa; }
tbody tr:hover { background: #eef; }
tfoot th, tfoot td { font-weight: bold; background: #f0f0f0; }

進階功能:排序、篩選、分頁

純 HTML/CSS 無法實現交互,需 JavaScript 庫:

常見錯誤避坑

  • ❌ 用表格做佈局 → ✅ 用 Flex/Grid
  • ❌ 缺少 <caption> 和 scope
  • ❌ 在 <td> 內嵌套 <div> 做佈局 → 直接用 CSS
  • ❌ 合併單元格後未處理無障礙關聯
  • ❌ 長數字未用 tabular-nums 導致對齊混亂

總結

HTML 表格是展示結構化數據的最佳語義容器。掌握 <caption>、<thead/tbody/tfoot>、<th scope>、<colgroup> 等核心要素,配合現代 CSS 與無障礙屬性,能構建專業、可用、可維護的數據展示界面。

copyright © 萬盛學電腦網 all rights reserved