表格不只是「顯示 Excel 資料」的工具。在 CSS 佈局普及前,它是唯一的頁面佈局手段;今天,它仍是結構化數據的標準容器:財報、課表、比價表、賽程表、後台管理列表……凡是「行列對齊、需對比、可排序」的資料,表格都是首選。
| 標籤 | 全名 | 角色 | 巢狀關係 |
|---|---|---|---|
<table> | Table | 表格容器,定義邊界與整體屬性 | 最外層 |
<tr> | Table Row | 表格行,包裹一組水平儲存格 | <table> 直系子元素 |
<td> | Table Data | 資料儲存格,承載實際內容 | <tr> 直系子元素 |
<th> | Table Header | 表頭儲存格,語義化標示標題,預設粗體置中 | <tr> 直系子元素 |
<table>
<tr>
<th>姓名</th>
<th>年齡</th>
</tr>
<tr>
<td>小明</td>
<td>18</td>
</tr>
</table>
<table>
<caption>班級學生名單</caption> <!-- 表格標題,無障礙關鍵 -->
<thead> <!-- 表頭區塊 -->
<tr><th scope="col">姓名</th><th scope="col">年齡</th></tr>
</thead>
<tbody> <!-- 主體資料區 -->
<tr><td>小明</td><td>18</td></tr>
<tr><td>小華</td><td>19</td></tr>
</tbody>
<tfoot> <!-- 彙總/頁尾區 -->
<tr><th>總計</th><td>2 人</td></tr>
</tfoot>
</table>
優勢: 列印時 <thead>/<tfoot> 可自動重複顯示;JS 排序/分頁邏輯更清晰;螢幕閱讀器導航更友善。
| 功能 | HTML 屬性(棄用/不推薦) | CSS 替代(標準做法) |
|---|---|---|
| 表格寬度 | width="600" | width: 600px; / width: 100%; |
| 邊框寬度 | border="1" | border: 1px solid #ccc; + border-collapse: collapse; |
| 儲存格間距 | cellspacing="5" | border-collapse: separate; border-spacing: 5px; |
| 內容邊距 | cellpadding="10" | padding: 10px;(寫在 td, th) |
| 背景顏色 | bgcolor="#f0f0f0" | background-color: #f0f0f0; |
| 背景圖片 | background="bg.jpg" | background-image: url(bg.jpg); |
| 水平對齊 | align="center" | text-align: center; |
| 垂直對齊 | valign="top" | vertical-align: top; |
colspan/rowspan、固定寬度欄、對齊方式table > caption? > thead > tr > th[scope] > tbody > tr > td > tfoot?<div> 模擬表格(無語義、無原生鍵盤導航、無列印重複表頭)<td> 內塞入 <table> 巢狀 3 層以上(維護地獄)<caption> 和 scope,導致無障礙評分極低contenteditable 讓儲存格可編輯表格看似簡單,精通者寡。從今天開始,每寫一個 <table> 就問自己:這語義正確嗎?無障礙做到了嗎?手機能看嗎?