基本表格語法掌握後,下一步是學會處理複雜資料結構:跨行跨列合併、語意化表頭分組、無障礙屬性加持。本文透過實戰範例,示範專業級表格的完整寫法。
語意化表格建議使用下列分組標籤:
<table>
<caption>月銷售報表(2024 年 Q1)</caption>
<thead>
<tr><th scope="col">月份</th><th scope="col">營業額</th><th scope="col">成長率</th></tr>
</thead>
<tbody>
<tr><th scope="row">1 月</th><td>$1,200,000</td><td>+12%</td></tr>
<tr><th scope="row">2 月</th><td>$1,350,000</td><td>+15%</td></tr>
<tr><th scope="row">3 月</th><td>$1,280,000</td><td>+8%</td></tr>
</tbody>
<tfoot>
<tr><th scope="row">合計</th><td>$3,830,000</td><td>+11.7%</td></tr>
</tfoot>
</table>
關鍵屬性:
scope="col":標示該儲存格為「直欄表頭」scope="row":標示該儲存格為「橫列表頭」<caption>:表格標題,螢幕閱讀器會優先朗讀<table border="1" cellpadding="8" cellspacing="0" style="border-collapse:collapse; width:100%;">
<tr style="background:#f0f0f0;">
<th rowspan="2">產品類別</th>
<th colspan="2">2023 年</th>
<th colspan="2">2024 年</th>
</tr>
<tr style="background:#f0f0f0;">
<th>Q1</th><th>Q2</th><th>Q1</th><th>Q2</th>
</tr>
<tr>
<td>手機</td><td>500</td><td>550</td><td>600</td><td>620</td>
</tr>
<tr>
<td>筆電</td><td>300</td><td>320</td><td>350</td><td>380</td>
</tr>
<tr>
<td>配件</td><td>150</td><td>180</td><td>200</td><td>210</td>
</tr>
</table>
解析:
rowspan="2")colspan="2")/* 表格基礎重置 */
table {
border-collapse: collapse; /* 合併邊框 */
width: 100%;
font-family: inherit;
font-size: 0.95rem;
}
th, td {
border: 1px solid #ddd;
padding: 0.75rem 1rem;
text-align: left;
}
thead th {
background: #f8f9fa;
font-weight: 600;
position: sticky;
top: 0; /* 表頭固定 */
z-index: 1;
}
tbody tr:nth-child(even) {
background: #fafafa; /* 斑馬紋 */
}
tbody tr:hover {
background: #eef7ff; * 滑鼠懸停高亮 */
}
caption {
caption-side: bottom;
padding: 0.5rem;
font-size: 0.875rem;
color: #666;
}
小螢幕下表格易撐破版面,三種主流解法:
<div style="overflow-x:auto;"><table>...</table></div>th:first-child, td:first-child { position: sticky; left: 0; }@media (max-width: 600px) { thead { display:none; } tr { display:block; margin-bottom:1rem; } td { display:flex; justify-content:space-between; } td::before { content: attr(data-label); font-weight:bold; } }<caption> 描述表格用途scope="col|row"id + headers 關聯(如多層表頭)summary 屬性(HTML5 已棄用)掌握進階表格技巧,不只能呈現複雜資料,更能確保所有使用者(含螢幕閱讀器使用者)都能平等取得資訊。下一個專案嘗試重構舊表格,加上 scope、caption、響應式容器,體驗專業級的差異!