萬盛學電腦網

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

HTML 表格 完整教程:結構、屬性、合併單元格、無障礙與響應式技巧

基本結構

<table border="1">
  <caption>月度銷售報表</caption>
  <thead>
    <tr>
      <th scope="col">月份</th>
      <th scope="col">銷售額</th>
      <th scope="col">增長率</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1 月</td>
      <td>¥12,000</td>
      <td>+5%</td>
    </tr>
    <tr>
      <td>2 月</td>
      <td>¥15,000</td>
      
+8%
合計 ¥27,000 +6.5%

核心標籤語義

標籤語義必選/可選
<table>表格容器必選
<caption>表格標題(無障礙關鍵)強烈建議
<thead>表頭行組建議
<tbody>主體行組建議(可多個)
<tfoot>尾部行組(摘要)可選
<tr>行必選
<th>標題單元格表頭必選
<td>數據單元格必選
<colgroup>/<col>列組/列定義(寬度、樣式)可選

關鍵屬性

  • scope="col|row|colgroup|rowgroup":明確 `` 作用範圍,**屏幕閱讀器依賴此屬性**。
  • colspan="n":橫向合併 n 列。
  • rowspan="n":縱向合併 n 行。
  • headers="id列表":複雜表格中將 `` 關聯多個 ``。

合併單元格示例

<table>
  <tr>
    <th rowspan="2">類別</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>
  <tr>
    <td>手機</td><td>100</td><td>120</td><td>130</td><td>150</td>
  </tr>
</table>

無障礙檢查清單

  • ☐ 有 `` 描述表格用途
  • ☐ `` 必加 `scope` 屬性
  • ☐ 複雜表格用 `headers` + `id` 關聯
  • ☐ 不用表格做佈局(改用 CSS Grid/Flex)
  • ☐ 響應式:小屏啟用橫向滾動或卡片式重構
    @media (max-width: 600px) {
      table, thead, tbody, th, td, tr { display: block; }
      thead { position: absolute; top: -9999px; } /* 隱藏表頭但保留語義 */
      tr { margin-bottom: 1rem; border: 1px solid #ddd; }
      td { display: flex; justify-content: space-between; padding: .5rem; }
      td::before { content: attr(data-label); font-weight: bold; } /* 需在 td 加 data-label */
    }
    

CSS 美化建議

table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background: #f5f5f5; font-weight: 600; }
tbody tr:nth-child(even) { background: #fafafa; }
tbody tr:hover { background: #eef; }
caption { caption-side: top; padding: 10px; font-size: 1.1em; font-weight: bold; }

結語

表格是承載結構化數據的最佳語義容器。規範使用 ``、``、``、合併屬性與響應式策略,能讓數據在所有設備、輔助技術下都清晰可讀。

copyright © 萬盛學電腦網 all rights reserved