| 屬性 | 作用對象 | 單位 | 預設值 | 說明 |
|---|---|---|---|---|
colspan | <td>, <th> | 正整數 | 1 | 水平合併欄位,跨越指定列數 |
rowspan | <td>, <th> | 正整數 | 1 | 垂直合併欄位,跨越指定行數 |
<table class="table-base">
<thead>
<tr>
<th rowspan="2">學期</th>
<th colspan="3">課程成績</th>
</tr>
<tr>
<th>數學</th><th>英文</th><th>程式設計</th>
</tr>
</thead>
<tbody>
<tr><td>大一上</td><td>92</td><td>88</td><td>95</td></tr>
<tr><td>大一下</td><td>89</td><td>91</td><td>97</td></tr>
</tbody>
</table>
關鍵邏輯: 第一列 <th rowspan="2"> 佔據兩行;第二列 <th colspan="3"> 佔據三列,因此第二行只需定義三個子欄位 <th>,總欄位數保持 4 列一致。
<table class="table-base">
<thead>
<tr>
<th rowspan="3">學生資訊</th>
<th colspan="2">期中考</th>
<th colspan="2">期末考</th>
<th rowspan="3">加權總分</th>
</tr>
<tr>
<th colspan="2">筆試</th>
<th colspan="2">實作</th>
</tr>
<tr>
<th>理論</th><th>實務</th><th>專案</th><th>報告</th>
</tr>
</thead>
<tbody>
<tr>
<td>張三</td><td>85</td><td>90</td><td>88</td><td>92</td><td>89</td>
</tr>
</tbody>
</table>
三層表頭巢狀結構,每層 colspan 總和必須等於最底層葉子節點數(此處 4),rowspan 則確保垂直跨度正確。
border: 1px solid red 視覺化檢查。rowspan 會「吃掉」下方行的對應欄位,下一行**不應**再寫入該欄位的 <td>。
<!-- 錯誤示範 -->
<tr><td rowspan="2">A</td><td>B</td></tr>
<tr><td>C</td><td>D</td></tr> <!-- 這行會多出一欄,導致結構崩壞 -->
<!-- 正確寫法 -->
<tr><td rowspan="2">A</td><td>B</td></tr>
<tr><td>C</td></tr> <!-- 只有 B 欄位,A 已被 rowspan 佔用 -->
scope="colgroup" 或 scope="rowgroup",輔助螢幕閱讀器理解範圍。/* 跨列/跨行標題置中加粗 */
th[colspan], th[rowspan] {
text-align: center;
font-weight: 700;
background: linear-gradient(180deg, #f8f9fa, #eef1f5);
}
/* 合併儲存格內部內容垂直置中 */
td[rowspan], th[rowspan] {
vertical-align: middle;
display: table-cell; /* 確保垂直置中生效 */
}
/* 視覺分隔:合併邊框加粗 */
th[colspan="2"] { border-right: 2px solid #2c3e50; }
th[colspan="3"] { border-right: 2px solid #2c3e50; }
合併儲存格在小螢幕下極易導致橫向滾動或內容擠壓。建議:
table-layout: fixed 並明確定義 <col> 寬度。若資料結構極其複雜(多層群組、小計、總計),純 HTML 表格難以維護。可考慮:
div 重構,使用 grid-column/row span 實現合併,語意更清晰、樣式控制更靈活。熟練掌握 colspan 與 rowspan,不只是會寫屬性,更要理解「表格網格模型」的佔用邏輯,才能構建結構正確、無障礙友善、易於維護的複雜資料表格。