萬盛學電腦網

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

HTML 表格標籤完整教學:table、caption、colgroup、thead、tbody、tfoot、tr、th、td 語意化結構

表格標籤全家桶:語意化結構、屬性對照、樣式鉤子與無障礙最佳實踐

完整結構範例

<table>
  <caption>2024 產品銷售統計</caption>
  <colgroup>
    <col style="width: 10%">   <!-- 序號 -->
    <col style="width: 30%">   <!-- 產品 -->
    <col style="width: 20%">   <!-- 單價 -->
    <col style="width: 20%">   <!-- 數量 -->
    <col style="width: 20%">   <!-- 小計 -->
  </colgroup>
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">產品名稱</th>
      <th scope="col">單價</th>
      <th scope="col">數量</th>
      <th scope="col">小計</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td>筆記型電腦</td>
      <td>$30,000</td>
      <td>5</td>
      <td>$150,000</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>滑鼠</td>
      <td>$500</td>
      <td>20</td>
      <td>$10,000</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th scope="rowgroup" colspan="4">總計</th>
      <td>$160,000</td>
    </tr>
  </tfoot>
</table>

標籤職責對照

標籤語意必要性關鍵屬性
<table>表格容器必須
<caption>表格標題/摘要強烈建議 (a11y)置於 table 直後
<colgroup>/<col>欄群組/欄定義建議 (固定版面)span, style="width:"
<thead>表頭行群組建議列印可重複顯示
<tbody>主體行群組隱含 (可省略標籤)可多個分組
<tfoot>表尾行群組建議 (摘要/統計)位置:thead 後、tbody 前或後
<tr>列必須
<th>表頭儲存格必須scope="col/row/colgroup/rowgroup", id, colspan/rowspan
<td>資料儲存格必須headers, colspan/rowspan

無障礙關鍵:scope 與 headers

  • scope="col":此 th 為欄標題 (預設)。
  • scope="row":此 th 為列標題 (首欄常用)。
  • scope="colgroup/rowgroup":跨欄/跨列標題。
  • headers="id1 id2":td 明確關聯多個 th (複雜合併時必需)。

CSS 鉤子建議

/* 針對語意化標籤撰寫樣式,避免依賴類別 */
table { border-collapse: collapse; width: 100%; }
caption { caption-side: top; padding: 1rem; font-weight: 600; }
colgroup col { /* 欄寬已在 HTML style 設定 */ }
thead th { background: #f5f5f5; border-bottom: 2px solid #333; }
tbody th[scope="row"] { background: #fafafa; font-weight: normal; text-align: left; }
tbody td { border-bottom: 1px solid #eee; }
tbody tr:hover { background: #e3f2fd; }
tfoot th, tfoot td { border-top: 2px solid #333; font-weight: 600; }

語意化表格結構 + CSS 針對標籤撰寫樣式,實現結構與表現分離,兼顧無障礙、SEO 與維護性。

copyright © 萬盛學電腦網 all rights reserved