萬盛學電腦網

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

HTML 表格顏色控制:bgcolor 廢棄屬性、CSS background-color、漸變、條紋、懸停與無障礙對比度

廢棄屬性(僅供維護舊專案參考)

<table bgcolor="#333366">           <!-- 整張表格背景 -->
<tr bgcolor="#00CC33">             <!-- 整列背景 -->
<td bgcolor="red">單元格</td>     <!-- 單元格背景 -->

現代專案嚴禁使用,請改用 CSS。

CSS 現代背景控制

<style>
.table { border-collapse: collapse; width: 100%; }
.table th, .table td { border: 1px solid #dee2e6; padding: 12px; }

/* 1. 整體背景 */
.table { background: #f8f9fa; }

/* 2. 表頭背景 */
.table thead th { background: #343a40; color: white; }

/* 3. 斑馬紋 (奇/偶列) */
.table tbody tr:nth-child(odd)  { background: #ffffff; }
.table tbody tr:nth-child(even) { background: #f1f3f5; }

/* 4. 懸停高亮 */
.table tbody tr:hover { background: #e7f1ff; }

/* 5. 特定欄/列高亮 */
.table td:nth-child(3) { background: #fff8e1; } /* 第 3 欄 */
.table tr.total td { background: #e8f5e9; font-weight: bold; } /* 總計列 */

/* 6. 線性漸變表頭 */
.table thead th { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }

/* 7. 列漸變 (視覺引導) */
.table tbody tr { background: linear-gradient(to right, transparent 50%, rgba(0,0,0,0.02) 50%); background-size: 100% 200%; }
.table tbody tr:hover { background-position: 0 100%; transition: background-position 0.3s; }
</style>

無障礙對比度檢查清單

  • 文字與背景對比度 ≥ 4.5:1 (AA) / 7:1 (AAA)。
  • 連結/按鈕焦點狀態可見(outline 不可移除)。
  • 色盲模擬測試:使用 DevTools Rendering 模擬 Protanopia/Deuteranopia。
  • 不單靠顏色傳達資訊(需配合圖標/文字/紋理)。

響應式表格背景固定表頭

.table-wrapper { overflow-x: auto; max-height: 60vh; overflow-y: auto; }
.table thead th { position: sticky; top: 0; z-index: 1; background: #343a40; color: white; }
copyright © 萬盛學電腦網 all rights reserved