表格僅用於展示表格化數據(二維數據矩陣),絕不可用於頁面佈局。語義正確的表格結構,配合 CSS 樣式,能提供優秀的可讀性、可排序性與無障礙訪問體驗。
<table>
<caption>2024 年 Q1 季度銷售報表</caption>
<thead>
<tr>
<th scope="col">產品</th>
<th scope="col">1 月</th>
<th scope="col">2 月</th>
<th scope="col">3 月</th>
<th scope="col">小計</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">產品 A</th>
<td>1,200</td>
<td>1,350</td>
<td>1,100</td>
<td>3,650</td>
</tr>
<tr>
<th scope="row">產品 B</th>
<td>980</td>
<td>1,020</td>
<td>1,150</td>
<td>3,150</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">總計</th>
<td>2,180</td>
<td>2,370</td>
<td>2,250</td>
<td>6,800</td>
</tr>
</tfoot>
</table>
| 標籤/屬性 | 說明 | 關鍵點 |
|---|---|---|
<caption> | 表格標題/說明 | 放在 <table> 直後,無障礙必備 |
<thead>/<tbody>/<tfoot> | 行分組 | 語義分組,支持獨立滾動、打印分頁 |
<th> | 表頭單元格 | 必加 scope="col|row|colgroup|rowgroup" |
<td> | 數據單元格 | 可用 headers 屬性關聯多個表頭 |
colspan/rowspan | 跨列/跨行合併 | 合併時注意無障礙 headers 關聯 |
<colgroup>/<col> | 列組/列定義 | 可為整列統一設置寬度、樣式 |
scope="col"(列頭)、scope="row"(行頭)<th id="p1"> + <td headers="p1 q1"><data value="1200">1,200</data>,時間用 <time>table { display: block; overflow-x: auto; } 或重構為卡片列表table {
border-collapse: collapse; /* 合併邊框,避免雙線 */
width: 100%;
font-variant-numeric: tabular-nums; /* 數字等寬對齊 */
}
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: #eef; }
tfoot th, tfoot td { font-weight: bold; background: #f0f0f0; }
純 HTML/CSS 無法實現交互,需 JavaScript 庫:
<caption> 和 scope<td> 內嵌套 <div> 做佈局 → 直接用 CSStabular-nums 導致對齊混亂HTML 表格是展示結構化數據的最佳語義容器。掌握 <caption>、<thead/tbody/tfoot>、<th scope>、<colgroup> 等核心要素,配合現代 CSS 與無障礙屬性,能構建專業、可用、可維護的數據展示界面。