萬盛學電腦網

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

HTML 表格跨列合併:colspan 與 rowspan 完整實戰指南

核心屬性

屬性作用值預設
colspan向右合併欄位正整數1
rowspan向下合併列正整數1

合併後,被覆蓋的儲存格必須從 HTML 移除,否則結構錯誤。

跨列合併 colspan 範例

<table border="1">
  <tr>
    <th colspan="2">Name</th>  <!-- 合併兩欄 -->
    <th>Age</th>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>30</td>
  </tr>
</table>

渲染結果:表頭「Name」跨越兩欄,對應下方 First/Last Name。

跨行合併 rowspan 範例

<table border="1">
  <tr>
    <th rowspan="2">Category</th> <!-- 合併兩列 -->
    <th>Item</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Apple</td>
    <td>$1</td>
  </tr>
  <tr>
    <td>Banana</td>
    <td>$2</td>
  </tr>
</table>

混合合併:複雜表頭結構

<table>
  <thead>
    <tr>
      <th rowspan="2">Product</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>...</tbody>
</table>

無障礙支援:scope 與 headers

合併儲存格時,螢幕閱讀器需明確知道關聯關係:

<th colspan="2" scope="colgroup">2023</th>
<th rowspan="2" scope="rowgroup">Product</th>

更複雜結構使用 headers 屬性:

<th id="y2023" colspan="2">2023</th>
<td headers="y2023 q1">100</td>

CSS 樣式控制合併儲存格

th[colspan], td[colspan] { text-align: center; }
th[rowspan], td[rowspan] { vertical-align: middle; }
/* 針對合併儲存格調整對齊 */

常見錯誤與除錯

  1. 少算欄位數:合併後該列剩餘 <td> 數 + colspan 總和 ≠ 表格總欄數。
  2. 跨 <thead>/<tbody> 合併:rowspan 不跨區塊,需在同一區塊內。
  3. 巢狀表格干擾:內層表格的合併不影響外層計算。
  4. CSS display: flex/grid 破壞表格語意:合併屬性失效,勿在 <table> 使用非預設 display。

現代替代:CSS Grid 模擬表格合併

.grid-table {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}
.header-span { grid-column: span 2; }
.side-span { grid-row: span 2; }

適合非表格資料的版面排版,語意上不再是資料表。

延伸閱讀

copyright © 萬盛學電腦網 all rights reserved