<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 |
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;
}
.table-wrap { overflow-x: auto; }th:first-child, td:first-child { position: sticky; left: 0; }tr 變 block,配合 data-label 偽元素<caption> 描述表格用途<th> 有 scope 屬性id/headers 明確關聯