| 屬性 | 作用 | 值 | 適用元素 | ||
|---|---|---|---|---|---|
| `rowspan` | 向下合併列(垂直跨列) | 正整數,預設 1 | ` | `, ` | ` |
| `colspan` | 向右合併欄(水平跨欄) | 正整數,預設 1 | ` | `, ` | ` |
<table>
<caption>員工技能矩陣</caption>
<thead>
<tr>
<th rowspan="2">姓名</th>
<th colspan="3">程式語言</th>
<th rowspan="2">備註</th>
</tr>
<tr>
<th>JavaScript</th>
<th>Python</th>
<th>Go</th>
</tr>
</thead>
<tbody>
<tr>
<td>小明</td>
<td>★★★★★</td>
<td>★★★★☆</td>
<td>★★★☆☆</td>
<td>全端</td>
</tr>
<tr>
<td>小美</td>
<td>★★★★☆</td>
<td>★★★★★</td>
<td>★★☆☆☆</td>
<td>後端</td>
</tr>
</tbody>
</table>
**關鍵邏輯**:被合併的儲存格**不寫入 HTML**,由瀏覽器自動佔據空間。上例中,第一列 `姓名` 和 `備註` 佔兩列,`程式語言` 橫跨三欄,第二列才放三個子項目。
<table>
<thead>
<tr>
<th rowspan="3">部門</th>
<th colspan="2">上半年</th>
<th colspan="2">下半年</th>
</tr>
<tr>
<th colspan="2">Q1</th>
<th colspan="2">Q2</th>
</tr>
<tr>
<th>收入</th><th>成本</th>
<th>收入</th><th>成本</th>
</tr>
</thead>
<tbody>
<tr>
<td>業務部</td>
<td>100</td><td>40</td>
<td>120</td><td>50</td>
</tr>
</tbody>
</table>
合併儲存格會破壞預設的標題關聯,需明確指定:
<table>
<thead>
<tr>
<th id="name" rowspan="2">姓名</th>
<th id="skills" colspan="3">技能</th>
</tr>
<tr>
<th id="js" headers="skills">JS</th>
<th id="py" headers="skills">Python</th>
<th id="go" headers="skills">Go</th>
</tr>
</thead>
<tbody>
<tr>
<td headers="name">小明</td>
<td headers="js skills">★★★★★</td>
<td headers="py skills">★★★★☆</td>
<td headers="go skills">★★★☆☆</td>
</tr>
</tbody>
</table>
/* 合併儲存格置中、加粗 */
th[rowspan], th[colspan], td[rowspan], td[colspan] {
text-align: center;
vertical-align: middle;
font-weight: 600;
}
/* 視覺分隔合併區塊 */
th[colspan] { border-bottom: 2px solid #333; }
th[rowspan] { border-right: 2px solid #333; }
| 錯誤 | 現象 | 修正 | ||
|---|---|---|---|---|
| 數字超出實際行/列數 | 版面崩潰、空白儲存格 | 精確計算:`rowspan` 不超過剩餘列數,`colspan` 不超過剩餘欄數 | ||
| 忘記移除被合併的 ` | `/` | ` | 多出儲存格、結構錯亂 | 被合併的儲存格**完全不寫在 HTML** |
| 巢狀表格導致合併失效 | 內層表格獨立計算 | 避免巢狀表格,改用單一表格 + 合併 |
掌握 `rowspan`/`colspan` 邏輯,搭配 `scope`/`headers` 無障礙屬性,才能產出結構正確、無障礙友善的複雜資料表格。