萬盛學電腦網

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

HTML 表格製作完整教學:table、tr、td、th 與基本屬性

HTML 表格 (table) 基礎建構完整教學

HTML 表格用於呈現表格式資料 (tabular data),而非版面排版。正確結構包含 <table>、<tr> (列)、<th> (標題儲存格)、<td> (資料儲存格),並可加入 <caption>、<thead>/<tbody>/<tfoot> 等語意區段。

基本 3x3 空白表格範例

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>基本表格範例</title>
  <style>
    table { border-collapse: collapse; width: 100%; max-width: 400px; margin: 1rem auto; }
    th, td { border: 1px solid #333; padding: 8px; text-align: center; }
    th { background: #f0f0f0; }
  </style>
</head>
<body>
  <table>
    <caption>三行三列範例表格</caption>
    <thead>
      <tr><th>欄位 A</th><th>欄位 B</th><th>欄位 C</th></tr>
    </thead>
    <tbody>
      <tr><td>資料 1</td><td>資料 2</td><td>資料 3</td></tr>
      <tr><td>資料 4</td><td>資料 5</td><td>資料 6</td></tr>
      <tr><td>資料 7</td><td>資料 8</td><td>資料 9</td></tr>
    </tbody>
  </table>
</body>
</html>

核心標籤說明

標籤全名功能必要性
<table>Table表格容器必須
<caption>Caption表格標題/說明,置於 table 直後,利於無障礙建議
<thead>Table Head表頭區段 (標題列群組)建議
<tbody>Table Body主要資料區段建議
<tfoot>Table Foot表尾區段 (總計、備註)選用
<tr>Table Row列容器必須
<th>Table Header標題儲存格,預設粗體置中,scope="col|row" 指定範圍表頭必須
<td>Table Data資料儲存格必須

常用屬性 (HTML5 建議改用 CSS)

  • border:邊框寬度 (像素),border="1" 顯示細線。
  • cellpadding:儲存格內邊距 (內容到邊框)。
  • cellspacing:儲存格間距 (邊框之間)。
  • width:表格寬度 (像素或百分比)。
  • align:表格水平對齊 (left|center|right)。

現代最佳實務:移除所有表格表現屬性,完全交由 CSS 控制 (border-collapse, padding, margin, width),結構與樣式分離。

語意化表格檢查清單

  1. 是否有 <caption> 描述表格用途?
  2. <th> 是否加 scope="col" 或 scope="row"?
  3. 是否使用 <thead>/<tbody>/<tfoot> 區分區段?
  4. 複雜表格是否需要 <colgroup> 定義欄寬?

正確的表格結構,讓螢幕閱讀器使用者也能輕鬆理解資料關係。

copyright © 萬盛學電腦網 all rights reserved