<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="col":此 th 為欄標題 (預設)。scope="row":此 th 為列標題 (首欄常用)。scope="colgroup/rowgroup":跨欄/跨列標題。headers="id1 id2":td 明確關聯多個 th (複雜合併時必需)。/* 針對語意化標籤撰寫樣式,避免依賴類別 */
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 與維護性。