萬盛學電腦網

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

HTML 表格進階範例:合併儲存格、表頭結構與無障礙實作

基本表格語法掌握後,下一步是學會處理複雜資料結構:跨行跨列合併、語意化表頭分組、無障礙屬性加持。本文透過實戰範例,示範專業級表格的完整寫法。

進階表格架構標籤

語意化表格建議使用下列分組標籤:

<table>
  <caption>月銷售報表(2024 年 Q1)</caption>
  <thead>
    <tr><th scope="col">月份</th><th scope="col">營業額</th><th scope="col">成長率</th></tr>
  </thead>
  <tbody>
    <tr><th scope="row">1 月</th><td>$1,200,000</td><td>+12%</td></tr>
    <tr><th scope="row">2 月</th><td>$1,350,000</td><td>+15%</td></tr>
    <tr><th scope="row">3 月</th><td>$1,280,000</td><td>+8%</td></tr>
  </tbody>
  <tfoot>
    <tr><th scope="row">合計</th><td>$3,830,000</td><td>+11.7%</td></tr>
  </tfoot>
</table>

關鍵屬性:

  • scope="col":標示該儲存格為「直欄表頭」
  • scope="row":標示該儲存格為「橫列表頭」
  • <caption>:表格標題,螢幕閱讀器會優先朗讀

合併儲存格實戰範例

<table border="1" cellpadding="8" cellspacing="0" style="border-collapse:collapse; width:100%;">
  <tr style="background:#f0f0f0;">
    <th rowspan="2">產品類別</th>
    <th colspan="2">2023 年</th>
    <th colspan="2">2024 年</th>
  </tr>
  <tr style="background:#f0f0f0;">
    <th>Q1</th><th>Q2</th><th>Q1</th><th>Q2</th>
  </tr>
  <tr>
    <td>手機</td><td>500</td><td>550</td><td>600</td><td>620</td>
  </tr>
  <tr>
    <td>筆電</td><td>300</td><td>320</td><td>350</td><td>380</td>
  </tr>
  <tr>
    <td>配件</td><td>150</td><td>180</td><td>200</td><td>210</td>
  </tr>
</table>

解析:

  • 第一列「產品類別」向下跨兩列(rowspan="2")
  • 「2023 年」與「2024 年」各向右跨兩列(colspan="2")
  • 第二列細分為 Q1、Q2 兩季

CSS 樣式最佳化

/* 表格基礎重置 */
table {
  border-collapse: collapse;  /* 合併邊框 */
  width: 100%;
  font-family: inherit;
  font-size: 0.95rem;
}
th, td {
  border: 1px solid #ddd;
  padding: 0.75rem 1rem;
  text-align: left;
}
thead th {
  background: #f8f9fa;
  font-weight: 600;
  position: sticky;
  top: 0;            /* 表頭固定 */
  z-index: 1;
}
tbody tr:nth-child(even) {
  background: #fafafa;   /* 斑馬紋 */
}
tbody tr:hover {
  background: #eef7ff;   * 滑鼠懸停高亮 */
}
caption {
  caption-side: bottom;
  padding: 0.5rem;
  font-size: 0.875rem;
  color: #666;
}

響應式表格策略

小螢幕下表格易撐破版面,三種主流解法:

  1. 水平捲動容器(最簡單、資料完整性最高)
    <div style="overflow-x:auto;"><table>...</table></div>
  2. 關鍵欄固定、其餘捲動:th:first-child, td:first-child { position: sticky; left: 0; }
  3. 斷點重組為卡片:@media (max-width: 600px) { thead { display:none; } tr { display:block; margin-bottom:1rem; } td { display:flex; justify-content:space-between; } td::before { content: attr(data-label); font-weight:bold; } }

無障礙(a11y)檢核清單

  • [ ] 有 <caption> 描述表格用途
  • [ ] 所有表頭儲存格加 scope="col|row"
  • [ ] 複雜表頭使用 id + headers 關聯(如多層表頭)
  • [ ] 避免使用 summary 屬性(HTML5 已棄用)
  • [ ] 色彩對比度符合 WCAG AA(文字 4.5:1,大字 3:1)
  • [ ] 鍵盤可聚焦互動元素(連結、按鈕、輸入框)

掌握進階表格技巧,不只能呈現複雜資料,更能確保所有使用者(含螢幕閱讀器使用者)都能平等取得資訊。下一個專案嘗試重構舊表格,加上 scope、caption、響應式容器,體驗專業級的差異!

copyright © 萬盛學電腦網 all rights reserved