萬盛學電腦網

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

HTML 表格製作完整教學:結構、屬性、合併儲存格與無障礙

HTML 表格用於呈現結構化資料。本文完整說明 <table> 核心結構、語意化區塊、合併儲存格、無障礙屬性與現代 CSS 樣式建議。

基本結構

<table>
  <caption>月銷售報表</caption>
  <thead>
    <tr>
      <th scope="col">月份</th>
      <th scope="col">金額</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>1月</td><td>$10,000</td></tr>
    <tr><td>2月</td><td>$12,000</td></tr>
  </tbody>
  <tfoot>
    <tr><th scope="row">合計</th><td>$22,000</td></tr>
  </tfoot>
</table>

瀏覽器渲染預覽

月銷售報表
月份金額
1月$10,000
2月$12,000
合計$22,000

核心標籤與屬性

標籤用途關鍵屬性
<table>表格容器summary (已棄用,改用 caption/aria-describedby)
<caption>表格標題置於 table 之後第一個子元素
<thead>表頭群組列印時可重複顯示
<tbody>主體群組可有多個 tbody 分組
<tfoot>表尾群組摘要/合計列
<tr>列—
<th>表頭儲存格scope="col|row|colgroup|rowgroup"
<td>資料儲存格colspan, rowspan, headers

合併儲存格

  • colspan="n":橫向跨越 n 格
  • rowspan="n":縱向跨越 n 格
<tr>
  <th rowspan="2">類別</th>
  <th colspan="2">2023 年</th>
  <th colspan="2">2024 年</th>
</tr>
<tr>
  <th>Q1</th><th>Q2</th><th>Q1</th><th>Q2</th>
</tr>

現代 CSS 樣式建議

table { border-collapse: collapse; width: 100%; font-size: .9rem; }
th, td { padding: .5rem .75rem; border: 1px solid #dee2e6; text-align: left; }
thead { background: #343a40; color: #fff; }
tbody tr:nth-child(even) { background: #f8f9fa; }
tbody tr:hover { background: #e2e6ea; }
caption { caption-side: top; padding: .5rem; font-weight: 600; color: #495057; }

無障礙檢查清單

  • ✅ 有 <caption> 或 aria-describedby 說明表格用途
  • ✅ 所有表頭用 <th> 並加 scope 屬性
  • ✅ 複雜表格使用 headers 屬性關聯多層表頭
  • ✅ 避免用表格做版面佈局
copyright © 萬盛學電腦網 all rights reserved