表格是網頁排版的經典工具,雖然現代佈局改用 CSS Flexbox/Grid,但理解表格結構對處理表格資料、維護舊專案、製作 HTML Email 仍不可或缺。本文詳細說明三大核心標籤與基本語法。
三大核心標籤
| 標籤 | 全名 | 角色 | 必要性 |
<table> | Table | 表格容器,定義整個表格範圍 | 必須 |
<tr> | Table Row | 定義一列 | 必須(至少一列) |
<td> | Table Data | 定義一個儲存格(資料儲存格) | 必須(每列至少一格) |
補充: 表頭儲存格用 <th>(Table Header),語意為標題列,預設粗體置中。
基本語法結構
<table>
<tr>
<td>儲存格 1-1</td>
<td>儲存格 1-2</td>
<td>儲存格 1-3</td>
</tr>
<tr>
<td>儲存格 2-1</td>
<td>儲存格 2-2</td>
<td>儲存格 2-3</td>
</tr>
<!-- 更多列 -->
</table>
常用屬性速查(HTML5 建議改用 CSS)
| 屬性 | 適用標籤 | 說明 | CSS 替代 |
border | table | 外框+內框粗細 | border, border-collapse |
width | table | 表格寬度 | width |
height | table, td, th | 高度 | height, min-height |
cellspacing | table | 儲存格間距 | border-spacing |
cellpadding | table | 儲存格內邊距 | padding (在 td/th) |
align | table | 表格水平對齊 | margin-left/right: auto |
bgcolor | table, tr, td, th | 背景色 | background-color |
colspan | td, th | 橫跨欄數 | (無直接替代,結構屬性) |
rowspan | td, th | 橫跨列數 | (無直接替代,結構屬性) |
valign | tr, td, th | 垂直對齊 | vertical-align |
align | td, th | 水平對齊 | text-align |
完整範例:合併儲存格
<table border="1" cellpadding="5" cellspacing="0">
<tr>
<th colspan="2">2024 年課程表</th>
<th>講師</th>
</tr>
<tr>
<td rowspan="2">前端基礎</td>
<td>HTML5</td>
<td>王老師</td>
</tr>
<tr>
<td>CSS3</td>
<td>李老師</td>
</tr>
<tr>
<td>JavaScript</td>
<td>ES6+</td>
<td>張老師</td>
</tr>
</table>
語意化輔助標籤(HTML4/HTML5 共用)
<caption>:表格標題,置於 <table> 直後,無障礙必備。
<thead>, <tbody>, <tfoot>:分組列,支援列表排序、列印時重複表頭。
<colgroup>, <col>:欄群組,批次設定欄寬/樣式。
<table>
<caption>月度銷售報表</caption>
<colgroup>
<col style="width: 30%;">
<col style="width: 70%;">
</colgroup>
<thead>
<tr><th>月份</th><th>金額</th></tr>
</thead>
<tbody>
<tr><td>1 月</td><td>$10,000</td></tr>
</tbody>
<tfoot>
<tr><th>總計</th><th>$10,000</th></tr>
</tfoot>
</table>
無障礙與 SEO 重點
- 資料表格必須有
<caption> 或 aria-label 描述用途。
2. 表頭儲存格必須用 <th>,並加 scope="col|row|colgroup|rowgroup" 明確關聯。
3. 複雜表格使用 headers 屬性關聯多個表頭:<td headers="h1 h2">。
4. 避免用表格做版面佈局(role="presentation" 可標示純佈局表格)。
5. 響應式表格:小螢幕啟用橫向捲動或轉為卡片式顯示。