HTML 表格 (<table>) 用於呈現「表格式資料」,非版面佈局工具。本文從基本結構、語義標籤、合併儲存格、無障礙屬性,延伸至 CSS 樣式與響應式處理,完整掌握表格開發。
<table>
<caption>月份銷售報表</caption>
<thead>
<tr>
<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>$10,000</td>
<td>$4,000</td>
<td>$6,000</td>
</tr>
<tr>
<th scope="row">2 月</th>
<td>$12,000</td>
<td>$5,000</td>
<td>$7,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">總計</th>
<td>$22,000</td>
<td>$9,000</td>
<td>$13,000</td>
</tr>
</tfoot>
</table>
<table>:表格容器<caption>:表格標題/說明,放在 <table> 之後,利於無障礙與 SEO<thead>, <tbody>, <tfoot>:語義分組表頭、主體、表尾,支援列印分頁、捲動固定表頭<tr> (Table Row):表格列<th> (Table Header):表頭儲存格,**必加 scope="col|row|colgroup|rowgroup"** 明確關聯範圍<td> (Table Data):資料儲存格<td colspan="2"> — 佔據 2 欄<td rowspan="3"> — 佔據 3 列<tr>
<th rowspan="2">類別</th>
<th colspan="2">2023 年</th>
<th colspan="2">2024 年</th>
</tr>
<tr>
<th>Q1</th><th>Q2</th>
<th>Q1</th><th>Q2</th>
</tr>
| 屬性 | 用於 | 說明 |
|---|---|---|
scope | <th> | col (欄標題)、row (列標題)、colgroup, rowgroup — 螢幕閱讀器關鍵 |
headers | <td> | 引用對應 <th id="..."> 的 id,複雜表格必要 |
<caption> | <table> | 表格標題,螢幕閱讀器優先朗讀 |
summary | <table> | HTML5 已棄用,改用 <caption> 或 <details> 包裹說明 |
table {
width: 100%;
border-collapse: collapse; /* 合併邊框,避免雙線 */
font-family: system-ui, sans-serif;
}
th, td {
border: 1px solid #ddd;
padding: 0.75rem 1rem;
text-align: left;
}
th {
background: #f8f9fa;
font-weight: 600;
white-space: nowrap; /* 表頭不換行 */
}
tbody tr:nth-child(even) {
background: #fafafa; /* 斑馬紋 */
}
tbody tr:hover {
background: #eef; /* 懸停高亮 */
}
caption {
caption-side: bottom; /* 標題置底 */
padding: 0.5rem;
font-style: italic;
color: #666;
}
行動裝置寬度不足顯示完整表格時,常見三種方案:
<div class="table-responsive">
<table>...</table>
</div>
.table-responsive {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
table { min-width: 600px; } /* 強制最小寬度觸發捲動 */
@media (max-width: 600px) {
table, thead, tbody, th, td, tr { display: block; }
thead { display: none; } /* 隱藏表頭,改用 data-label */
tr { margin-bottom: 1rem; border: 1px solid #ddd; border-radius: 4px; }
td {
display: flex; justify-content: space-between;
padding: 0.5rem; border: none; border-bottom: 1px solid #eee;
}
td::before {
content: attr(data-label);
font-weight: bold; color: #333;
}
td:last-child { border-bottom: none; }
}
HTML 需加 data-label 屬性:<td data-label="收入">$10,000</td>
使用 position: sticky 固定第一欄:
th:first-child, td:first-child {
position: sticky;
left: 0;
background: white;
z-index: 1;
box-shadow: 2px 0 4px rgba(0,0,0,0.1);
}
<ul>/<ol><dl> (定義清單)掌握語義化結構、無障礙屬性、CSS 美化與響應式策略,就能製作出專業、易用、可維護的 HTML 表格。