表格用於展示「二維結構化資料」,而非版面排版。正確的表格結構包含語意區塊、標題關聯、響應式處理與無障礙屬性。
<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.8</td>
<td>+8.1%</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">合計</th>
<td>26.3</td>
<td>-</td>
</tr>
</tfoot>
</table>
| 元素/屬性 | 用途 | 關鍵點 |
|---|---|---|
<caption> | 表格標題 | 放在 <table> 之後,螢幕閱讀器優先朗讀 |
<thead>/<tbody>/<tfoot> | 行群組語意化 | 列印時 thead/tfoot 可重複顯示;tfoot 可置底或置頂 |
<th scope="col|row|colgroup|rowgroup"> | 標題儲存格 | 無障礙關鍵:明確關聯範圍,螢幕閱讀器正確朗讀標題 |
<td> | 資料儲存格 | 可用 headers="id1 id2" 關聯複雜標題 |
colspan/rowspan | 跨欄/跨列合併 | 合併後該儲存格佔據多格空間,其他列需減少對應 td |
<colgroup>/<col> | 欄群組樣式 | 可對整欄設定寬度、對齊、背景,無需逐列重複 |
.table-wrapper { overflow-x: auto; -webkit-overflow-scrolling: touch; }
table { min-width: 600px; }
position: sticky):
th:first-child, td:first-child { position: sticky; left: 0; background: #fff; z-index: 1; }
@media (max-width: 600px) {
table, thead, tbody, th, td, tr { display: block; }
thead { display: none; } /* 隱藏標題列,改用 data-label */
td { position: relative; padding-left: 50%; }
td::before { content: attr(data-label); position: absolute; left: 1rem; font-weight: bold; }
}
<caption> 描述表格用途<th> 皆有 scope 屬性id/headers 關聯table {
border-collapse: collapse; /* 合併邊框,避免雙線 */
width: 100%;
font-variant-numeric: tabular-nums; /* 數字等寬對齊 */
}
th, td {
border: 1px solid #e0e0e0;
padding: 0.75rem 1rem;
text-align: left;
}
th { background: #f5f5f5; font-weight: 600; }
tbody tr:nth-child(even) { background: #fafafa; }
tbody tr:hover { background: #e3f2fd; }