萬盛學電腦網

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

HTML 表格顏色設定:CSS 取代 bgcolor 屬性的現代做法

HTML <table> 早期使用 bgcolor 屬性設定背景色,現代開發應全面改用 CSS。本文說明表格結構與 CSS 設定背景色的正確方式。

表格基本結構

<table>
  <thead>
    <tr><th>表頭 1</th><th>表頭 2</th></tr>
  </thead>
  <tbody>
    <tr><td>資料 1</td><td>資料 2</td></tr>
    <tr><td>資料 3</td><td>資料 4</td></tr>
  </tbody>
</table>

CSS 設定背景色(推薦)

table { border-collapse: collapse; width: 100%; }
th, td { padding: 8px; border: 1px solid #dee2e6; }

/* 表頭背景 */
thead { background-color: #343a40; color: #fff; }

/* 隔列變色(斑馬紋) */
tbody tr:nth-child(even) { background-color: #f8f9fa; }

/* 懸停高亮 */
tbody tr:hover { background-color: #e2e6ea; }

/* 特定儲存格 */
td.highlight { background-color: #fff3cd; }

進階:語意化區塊著色

thead { background: #2c3e50; color: #ecf0f1; }
tbody tr:nth-child(odd) { background: #ecf0f1; }
tbody tr:nth-child(even) { background: #fff; }
tfoot { background: #2c3e50; color: #ecf0f1; font-weight: bold; }

避免使用的舊屬性

  • <table bgcolor="#ccc">
  • <tr bgcolor="#eee">
  • <td bgcolor="#ffffcc">

這些屬性在 HTML5 已**棄用**,會導致驗證錯誤且難以維護。

無障礙提醒

  • 確保文字與背景對比度 ≥ 4.5:1(WCAG AA)
  • 使用 <th scope="col|row"> 建立表頭關聯
  • 提供 <caption> 說明表格用途
copyright © 萬盛學電腦網 all rights reserved