表格合併儲存格是呈現複雜資料結構的關鍵技術。colspan 合併橫向欄位 (跨列),rowspan 合併縱向列 (跨行)。正確使用需理解「佔據空間」與「後續儲存格位移」的邏輯。
| 屬性 | 全名 | 方向 | 值 | 效果 |
|---|---|---|---|---|
colspan | Column Span | 水平 (跨列/跨欄) | 正整數 (預設 1) | 該儲存格向右佔據 N 個欄位 |
rowspan | Row Span | 垂直 (跨行) | 正整數 (預設 1) | 該儲存格向下佔據 N 個列 |
當某儲存格設定 colspan="2",它佔據自己 + 右側 1 欄。**下一個 <td> 會自動跳到第 3 欄**。同理 rowspan 向下佔據,後續列對應欄位會被「跳過」。
<table class="demo-table">
<thead>
<tr>
<th rowspan="2">學生</th> <!-- 跨 2 列 (表頭+次表頭) -->
<th colspan="2">期中考</th> <!-- 跨 2 欄 -->
<th colspan="2">期末考</th> <!-- 跨 2 欄 -->
</tr>
<tr>
<th>國文</th><th>數學</th> <!-- 次表頭展開 -->
<th>國文</th><th>數學</th>
</tr>
</thead>
<tbody>
<tr><td>小明</td><td>85</td><td>92</td><td>88</td><td>95</td></tr>
<tr><td>小華</td><td>78</td><td>85</td><td>80</td><td>90</td></tr>
</tbody>
</table>
<table class="demo-table">
<thead>
<tr><th>分類</th><th>商品</th><th>價格</th></tr>
</thead>
<tbody>
<tr>
<td rowspan="3">電子產品</td> <!-- 佔據 3 列 -->
<td>筆電</td><td>$35,000</td>
</tr>
<tr> <!-- 此列無第 1 欄,被上列 rowspan 佔據 -->
<td>滑鼠</td><td>$590</td>
</tr>
<tr>
<td>鍵盤</td><td>$1,200</td>
</tr>
<tr>
<td rowspan="2">週邊</td> <!-- 佔據 2 列 -->
<td>滑鼠墊</td><td>$250</td>
</tr>
<tr>
<td>螢幕保護貼</td><td>$180</td>
</tr>
</tbody>
</table>
<table class="demo-table">
<thead>
<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>
</thead>
<tbody>
<tr>
<td rowspan="2">北區</th>
<td>120</td><td>135</td><td>140</td><td>155</td>
</tr>
<tr>
<td>110</td><td>125</td><td>130</td><td>145</td>
</tr>
<tr>
<td colspan="5" style="text-align:center; background:#f8f9fa;">總計:待計算</td>
</tr>
</tbody>
</table>
.demo-table {
width: 100%;
border-collapse: collapse;
font-size: 14px;
}
.demo-table th, .demo-table td {
border: 1px solid #dee2e6;
padding: 10px 12px;
text-align: center;
}
.demo-table thead th {
background: #2c3e50;
color: #fff;
font-weight: 600;
}
/* 合併儲存格加深背景、加粗 */
.demo-table [colspan], .demo-table [rowspan] {
background: #e8f4fd;
font-weight: 600;
}
/* 總計列 */
.demo-table tfoot td, .demo-table tr:last-child td {
background: #fff3cd;
font-weight: 700;
}
| 錯誤 | 現象 | 修正 |
|---|---|---|
| colspan 數值超過實際欄數 | 多出空白欄、版面破裂 | 計算總欄數,colspan 總和 ≤ 總欄數 |
| rowspan 導致後續列欄位錯位 | 資料塞錯欄位 | 畫表格草圖,標記被佔據格子,按序填入 td |
| 忘記移除被合併的 td/th | 多出儲存格、欄位數不符 | 被合併的格子**完全不寫**對應的 td/th |
| thead/tbody 內合併跨區段 | 語意錯誤、樣式異常 | rowspan 不跨越 thead/tbody/tfoot 邊界 |
scope="col" / scope="row" / scope="colgroup" / scope="rowgroup":明確標題範圍,螢幕閱讀器必備。scope,如 <th colspan="2" scope="colgroup">。<caption> 說明結構、id/headers 屬性關聯 (進階)。function generateMergedTable(data, mergeConfig) {
// mergeConfig: { rowspan: [(row, col, count)], colspan: [(row, col, count)] }
// 1. 建立二維陣列代表儲存格佔據狀態
// 2. 遍歷資料行,若位置被佔據 (occupied) 則跳過輸出 td
// 3. 遇到合併設定,輸出 td[rowspan/colspan],標記佔據區域
// 4. 輸出 HTML 字串
}
熟練 colspan/rowspan,能將扁平資料轉為清晰的分組報表,是後台管理、報表系統、資料視覺化的核心技能。