萬盛學電腦網

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

HTML <table> 標籤完整解析:結構元素、核心屬性、無障礙關聯、現代 CSS 重置與響應式策略

<table>:二維結構化資料的語意化容器

<table> 專為表格資料設計,非版面排版工具。正確結構包含 <caption>、<colgroup>/<col>、<thead>/<tbody>/<tfoot>、<tr>、<th>/<td>,並善用 scope/headers 建立無障礙關聯。

完整元素架構

<table>
  <caption>標題 (螢幕閱讀器優先朗讀)</caption>
  <colgroup>
    <col span="2"><col style="width: 40%;">
  </colgroup>
  <thead>
    <tr>
      <th scope="col">欄位 A</th>
      <th scope="col">欄位 B</th>
      <th scope="col">欄位 C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">列標題</th>
      <td>資料 1</td>
      <td>資料 2</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th scope="row">合計</th>
      <td>摘要 1</td>
      <td>摘要 2</td>
    </tr>
  </tfoot>
</table>

核心元素語意與屬性

元素語意關鍵屬性
<caption>表格標題/摘要無特殊屬性,CSS caption-side
<colgroup>欄群組span (跨欄數)
<col>單欄定義span, width (CSS)
<thead>表頭群組列印重複顯示
<tbody>主體群組可多個分組
<tfoot>表尾群組列印重複顯示,HTML5 可置頂或置底
<tr>列無特殊屬性
<th>標題儲存格scope="col|row|colgroup|rowgroup", id, abbr, colspan, rowspan
<td>資料儲存格headers="id1 id2", colspan, rowspan

現代 CSS 重置基礎樣式 (Normalize for Tables)

table {
  border-collapse: collapse;      /* 單線邊框,避免雙線 */
  border-spacing: 0;              /* 歸零 cellspacing */
  width: 100%;                    /* 預設滿寬 */
  font-variant-numeric: tabular-nums; /* 數字等寬對齊 */
  text-align: left;               /* 統一靠左,數字欄另行置右 */
}
th, td {
  padding: 0.75rem 1rem;          /* 取代 cellpadding */
  border: 1px solid var(--border-color, #e0e0e0);
  vertical-align: middle;         /* 內容置中 */
}
th {
  font-weight: 600;
  background: var(--header-bg, #f5f5f5);
  white-space: nowrap;            /* 標題預設不換行 */
}
tbody tr:nth-child(even) { background: var(--row-even, #fafafa); }
tbody tr:hover { background: var(--row-hover, #e3f2fd); }
caption {
  caption-side: top;
  padding: 0.5rem 1rem;
  font-weight: 500;
  text-align: left;
}

響應式三大策略 (擇一或組合)

  1. 水平捲動:.table-wrap { overflow-x: auto; }
  2. 關鍵欄固定:th:first-child, td:first-child { position: sticky; left: 0; }
  3. 卡片式轉換:Media Query 將 tr 變 block,配合 data-label 偽元素

無障礙檢查清單

  • [ ] 有 <caption> 描述表格用途
  • [ ] 所有 <th> 有 scope 屬性
  • [ ] 複雜表格使用 id/headers 明確關聯
  • [ ] 色彩對比度 ≥ 4.5:1 (AA)
  • [ ] 鍵盤可聚焦表格內互動元素
copyright © 萬盛學電腦網 all rights reserved