萬盛學電腦網

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

HTML 表格跨行跨列合併:rowspan、colspan 屬性完整教學與語意化結構

表格合併儲存格核心屬性:rowspan (跨列) 與 colspan (跨欄) 實戰指南

屬性定義

  • rowspan="n":當前儲存格向下跨佔 n 列 (含自身)。
  • colspan="n":當前儲存格向右跨佔 n 欄 (含自身)。
  • 值為正整數,0 在 HTML5 表示跨至該區塊結尾 (table/thead/tbody/tfoot),瀏覽器支援度不一,建議避免使用 0。

基礎範例:跨欄合併表頭

<table>
  <tr>
    <th colspan="2">2024 年上半年營收</th>
    <th colspan="2">2024 年下半年營收</th>
  </tr>
  <tr>
    <th>Q1</th><th>Q2</th><th>Q3</th><th>Q4</th>
  </tr>
  <tr>
    <td>100</td><td>120</td><td>130</td><td>150</td>
  </tr>
</table>

進階範例:跨列合併分類

<table>
  <tr>
    <th rowspan="3">水果</th>
    <td>蘋果</td><td>紅色</td>
  </tr>
  <tr>
    <td>香蕉</td><td>黃色</td>
  </tr>
  <tr>
    <td>葡萄</td><td>紫色</td>
  </tr>
  <tr>
    <th rowspan="2">蔬菜</th>
    <td>高麗菜</td><td>綠色</td>
  </tr>
  <tr>
    <td>紅蘿蔔</td><td>橙色</td>
  </tr>
</table>

混合跨行跨列

<tr>
  <th rowspan="2" colspan="2">合併 2列2欄</th>
  <td>C</td><td>D</td>
</tr>
<tr>
  <td>E</td><td>F</td>
</tr>

關鍵規則與避坑

  1. 被合併的儲存格不可再出現:rowspan="2" 佔據下一列對應位置,下一列對應位置的 <td> 必須省略。
  2. 每列儲存格總數 (含跨列佔用) 必須一致,否則瀏覽器會自動補齊/移位導致版面錯亂。
  3. 語意化優先:若資料結構允許,考慮拆分為多個簡單表格或使用 <dl>、CSS Grid 替代複雜合併。
  4. 無障礙:合併儲存格需配合 scope="colgroup/rowgroup" 或 headers 屬性關聯標題,螢幕閱讀器才能正確導航。

無障礙屬性補充

<th id="h1" rowspan="2">分類</th>
<th id="h2">名稱</th>
<th id="h3">顏色</th>
<tr>
  <td headers="h1 h2">蘋果</td>
  <td headers="h1 h3">紅色</td>
</tr>

掌握 rowspan/colspan 規則,能精確表達複雜資料結構,並配合無障礙屬性確保資訊無障礙傳遞。

copyright © 萬盛學電腦網 all rights reserved