萬盛學電腦網

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

HTML 表格製作入門:標準結構、屬性詳解、CSS 樣式化與響應式處理

標準表格骨架

<table>
  <caption>表格標題(螢幕閱讀器會朗讀)</caption>
  <thead>
    <tr>
      <th scope="col">欄位 1</th>
      <th scope="col">欄位 2</th>
      <th scope="col">欄位 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>資料 1-1</td>
      <td>資料 1-2</td>
      <td>資料 1-3</td>
    </tr>
    <tr>
      <td>資料 2-1</td>
      <td>資料 2-2</td>
      <td>資料 2-3</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3">合計/摘要資訊</td>
    </tr>
  </tfoot>
</table>

核心屬性對照(HTML5 建議改用 CSS)

屬性標籤說明CSS 替代
bordertable邊框寬度(像素)border: 1px solid #ccc
cellpaddingtable儲存格內邊距th,td{padding:8px}
cellspacingtable儲存格間距border-spacing: 0 (配合 collapse)
widthtable表格寬度width: 100% / max-width
aligntable表格水平對齊margin: 0 auto 置中
bgcolortable/tr/td背景色background-color
bordercolortable邊框顏色border-color

現代 CSS 樣式化範例

<style>
.table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
.table th, .table td { border: 1px solid #dee2e6; padding: 0.75rem; text-align: left; }
.table thead th { background: #f8f9fa; font-weight: 600; position: sticky; top: 0; z-index: 1; }
.table tbody tr:nth-child(even) { background: #fdfdfd; }
.table tbody tr:hover { background: #eef5ff; }
.table caption { caption-side: bottom; padding: 0.5rem; font-style: italic; color: #666; }
</style>

<div class="table-wrapper"> <!-- 響應式包裹 -->
  <table class="table">...</table>
</div>

響應式表格三大策略

  1. 水平滾動包裹:.table-wrapper { overflow-x: auto; }(最簡單、資料完整)。
  2. 關鍵欄固定:th:first-child, td:first-child { position: sticky; left: 0; }。
  3. 卡片式轉換:小螢幕下用 CSS Grid 將每列轉為卡片(需 JS 輔助或 data-label 屬性)。
copyright © 萬盛學電腦網 all rights reserved