萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML 表格跨行跨列合併 (rowspan/colspan) 完全指南

表格儲存格合併核心屬性詳解

rowspan (跨行) 與 colspan (跨列) 是構建複雜表格結構的關鍵屬性,掌握其計算邏輯避免結構錯誤。

核心屬性語法

<td rowspan="2">跨兩行</td>
<td colspan="3">跨三列</td>
<th rowspan="2" colspan="2">跨兩行兩列</th>
  • 值為正整數 ( ≥ 1 ),預設為 1
  • 可同時使用:rowspan="2" colspan="3"
  • 適用於 <td> 和 <th>

合併邏輯與計算規則

  1. 佔據空間:合併儲存格會佔據對應行/列的空間,後續儲存格自動跳過被佔據位置
  2. 聲明順序:按 HTML 來源順序 (左到右、上到下) 聲明合併儲存格
  3. 被佔據位置不再編寫 <td>:被合併的儲存格位置在代碼中省略

實戰範例:跨行合併

<table border="1">
  <tr>
    <th rowspan="2">姓名</th>
    <th colspan="2">成績</th>
  </tr>
  <tr>
    <th>數學</th>
    <th>英文</th>
  </tr>
  <tr>
    <td rowspan="2">張三</td>  <!-- 佔據第2、3行第1列 -->
    <td>90</td>
    <td>85</td>
  </tr>
  <tr>
    <!-- 此行第1列被上方 rowspan 佔據,不寫 td -->
    <td>95</td>
    <td>88</td>
  </tr>
</table>

視覺結構:

| 姓名 | 成績      |
|      | 數學 | 英文 |
| 張三 | 90   | 85   |
|      | 95   | 88   |  ← 第1列被合併

實戰範例:跨列合併

<table border="1">
  <tr>
    <th>產品</th>
    <th colspan="3">季度銷售額</th>  <!-- 佔據 Q1-Q3 三列 -->
  </tr>
  <tr>
    <th>Q1</th><th>Q2</th><th>Q3</th>
  </tr>
  <tr>
    <td>產品A</td>
    <td>100</td><td>120</td><td>110</td>
  </tr>
</table>

複雜合併:行列同時跨越

<table border="1">
  <tr>
    <th rowspan="2" colspan="2">類別</th>  <!-- 佔據 2行×2列 -->
    <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>
  <tr>
    <td rowspan="2">電子</td>  <!-- 佔據 2行 -->
    <td>手機</td>
    <td>500</td><td>550</td><td>600</td><td>650</td>
  </tr>
  <tr>
    <td>筆電</td>
    <td>300</td><td>320</td><td>350</td><td>380</td>
  </tr>
</table>

常見錯誤與調試技巧

錯誤後果修正
合併儲存格數量超出表格邊界瀏覽器忽略超出部分,結構錯亂精確計算行列數,不超出 thead/tbody 範圍
被合併位置仍寫入 <td>額外儲存格擠入,導致後續欄位錯位被佔據位置完全省略對應 td/th
thead/tbody 邊界跨越合併語意錯誤,無障礙樹破壞合併不跨越 thead/tbody/tfoot 邊界
CSS 選中器失效:nth-child 計算包含被隱藏儲存格用 :nth-of-type 或添加 class 選中

無障礙增強

  • <th scope="col"> / scope="row" / scope="colgroup" / scope="rowgroup":明確標題範圍
  • 合併標題務必加 scope 屬性
  • 複雜表格添加 <caption> 說明結構

CSS 樣式建議

table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background: #f5f5f5; font-weight: 600; }
/* 合併儲存格垂直居中 */
td[rowspan], th[rowspan] { vertical-align: middle; }

合併儲存格威力強大但易出錯,建議:先畫草圖規劃結構 → 寫 HTML 骨架 → 逐行填充內容 → 驗證無障礙 → 應用樣式。

copyright © 萬盛學電腦網 all rights reserved