萬盛學電腦網

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

HTML 表格製作實戰:語意化結構、屬性完整對照、響應式與無障礙最佳實踐

HTML 表格完整實作指南:從基礎結構到現代響應式策略

表格專為「二維結構化資料」設計。正確的標記包含 <caption>、<thead>/<tbody>/<tfoot>、<th scope>,確保語意、無障礙與 SEO 最佳化。

標準表格結構範本

<table>
  <caption>月度銷售報表</caption>
  <colgroup>
    <col span="2" style="width: 30%;">
    <col style="width: 40%;">
  </colgroup>
  <thead>
    <tr>
      <th scope="col">產品</th>
      <th scope="col">數量</th>
      <th scope="col">金額</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">筆記型電腦</th>
      <td>120</td>
      <td>NT$ 7,200,000</td>
    </tr>
    <tr>
      <th scope="row">滑鼠</th>
      <td>850</td>
      <td>NT$ 425,000</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th scope="row">合計</th>
      <td>970</td>
      <td>NT$ 7,625,000</td>
    </tr>
  </tfoot>
</table>

核心屬性完整對照

屬性適用元素說明現代替代
bordertable邊框寬度 (HTML 屬性,建議用 CSS)CSS border
cellspacingtable儲存格間距 (HTML 屬性,建議用 CSS)CSS border-collapse: collapse + border-spacing
cellpaddingtable儲存格內邊距 (HTML 屬性)CSS padding on th, td
aligntable表格水平對齊 (left/center/right)CSS margin-inline: auto 或 Flex/Grid
widthtable, td, th寬度 (像素/百分比)CSS width
bgcolortable, tr, td, th背景色 (HTML 屬性)CSS background-color
colspantd, th跨欄合併標準屬性,保留使用
rowspantd, th跨列合併標準屬性,保留使用
scopeth標題關聯範圍 (col/row/colgroup/rowgroup)無障礙關鍵,必填
headerstd, th關聯標題 ID 列表 (複雜表格)標準屬性,保留使用
nowraptd, th禁止換行 (已棄用)CSS white-space: nowrap

響應式表格三大策略

  1. 容器水平捲動:.table-wrap { overflow-x: auto; } 保持資料完整
  2. 關鍵欄固定:th:first-child { position: sticky; left: 0; } 凍結首欄
  3. 卡片式轉換:Media Query 將 tr 變 display: block,配合 data-label 偽元素顯示欄位名

無障礙檢查清單

  • [ ] <caption> 簡述表格內容
  • [ ] 所有 <th> 有 scope 屬性
  • [ ] 複雜表格用 id/headers 明確關聯
  • [ ] 文字對比度 ≥ 4.5:1
  • [ ] 鍵盤可導航至表格內互動元素
copyright © 萬盛學電腦網 all rights reserved