表格用於呈現表格式資料,而非版面配置。正確的語意結構能提升無障礙體驗與 SEO。本文涵蓋標籤結構、必要屬性、合併儲存格、響應式處理與樣式建議。
<table>
<caption>月份銷售報表</caption>
<thead>
<tr>
<th scope="col">月份</th>
<th scope="col">營業額</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1 月</th>
<td>$12,000</td>
</tr>
<tr>
<th scope="row">2 月</th>
<td>$15,500</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">總計</th>
<td>$27,500</td>
</tr>
</tfoot>
</table>
| 標籤 | 用途 | 關鍵屬性 |
|---|---|---|
<table> | 表格容器 | summary (已棄用,改用 <caption> 或 aria-describedby) |
<caption> | 表格標題,置於 <table> 之後 | 配合 caption-side CSS 控制位置 |
<thead>, <tbody>, <tfoot> | 表頭、主體、表尾區塊 | 列印時可重複表頭/表尾 |
<tr> | 列 | — |
<th> | 標題儲存格 | scope="col|row|colgroup|rowgroup", colspan, rowspan |
<td> | 資料儲存格 | colspan, rowspan, headers (關聯多個 th id) |
<colgroup>, <col> | 欄群組與欄屬性 | span, width, CSS 樣式化整欄 |
<td colspan="2"> 佔據兩欄。<td rowspan="3"> 佔據三列。<caption> 描述表格用途。<th> 加上 scope 屬性,讓螢幕閱讀器知道是列標題還是欄標題。headers 屬性於 <td> 關聯多個 <th id>。summary 屬性(HTML5 棄用)。<div style="overflow-x:auto"><table>...</table></div> 保持結構完整。display: block 將每列變卡片,配合 data-label 屬性顯示欄位名。<td data-label="月份">1 月</td>
td::before { content: attr(data-label); font-weight: bold; }@media (max-width: 600px) { .optional-col { display: none; } }。border, cellpadding, cellspacing, width, align, bgcolor, frame, rules 等。border-collapse: collapse;, padding, width, margin: 0 auto;, background-color。遵循語意化結構,表格既美觀又無障礙。