<table> 專為**表格化資料**設計,非佈局工具。正確使用語意標籤、無障礙屬性與響應式策略,能讓資料在各裝置、輔助科技上完美呈現。
<table>
<caption>2024 年各季營收統計</caption>
<thead>
<tr>
<th scope="col">季度</th>
<th scope="col">營收 (億元)</th>
<th scope="col">成長率</th>
</tr>
</thead>
<tbody>
<tr><th scope="row">Q1</th><td>12.5</td><td>+5.2%</td></tr>
<tr><th scope="row">Q2</th><td>13.1</td><td>+4.8%</td></tr>
</tbody>
<tfoot>
<tr><th scope="row">合計</th><td>25.6</td><td>+5.0%</td></tr>
</tfoot>
</table>
| 標籤 | 角色 | 必要屬性/備註 |
|---|---|---|
<caption> | 表格標題/摘要 | 緊跟 <table> 之後,螢幕閱讀器優先朗讀 |
<thead> | 表頭群組 | 列印時可重複表頭,scope="col" 關聯欄 |
<tbody> | 主體群組 | 可多個分組,scope="row" 關聯列 |
<tfoot> | 表尾群組 | 合計/平均,位置可置於 <tbody> 前後 |
<th> | 標題儲存格 | 必加 scope="col|row|colgroup|rowgroup" |
<td> | 資料儲存格 | 可用 headers="id1 id2" 關聯複雜表頭 |
<colgroup>/<col> | 欄群組/欄定義 | 套用寬度、樣式至整欄,span 合併欄 |
colspan="n":橫向跨欄rowspan="n":縱向跨列<tr>
<th rowspan="2">類別</th>
<th colspan="2">2024</th>
</tr>
<tr>
<th>上半年</th><th>下半年</th>
</tr>
<caption> 提供表格摘要<th scope="col|row"> 明確關聯維度id + headers 多對多關聯summary 屬性(HTML5 棄用),改用 <caption> 或 <details>.table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
table { min-width: 600px; } /* 強制觸發捲動 */
@media (max-width: 600px) {
table, thead, tbody, th, td, tr { display: block; }
thead { position: absolute; left: -9999px; } /* 隱藏但保留語意 */
tr { border: 1px solid #ddd; margin-bottom: 1rem; }
td { border: none; border-bottom: 1px solid #eee; position: relative; padding-left: 50%; }
td::before { content: attr(data-label); position: absolute; left: 1rem; font-weight: bold; }
}
<td data-label="營收 (億元)">12.5</td>
th:first-child, td:first-child { position: sticky; left: 0; background: #fff; z-index: 1; }
<nav><ul><li><a><article> + Grid<label> + <input> + CSS表格是資料的骨架,語意正確、無障礙完善、響應靈活,才能稱為專業級實作。