設定表格儲存格背景色,舊式 HTML bgcolor 屬性已棄用,現代開發全面改用 CSS。本文比較兩種做法,並提供漸層、條件式著色、無障礙對比度等進階技巧。
<!-- 不建議使用 -->
<table>
<tr>
<td bgcolor="#e91e6f">儲存格 1</td>
<td bgcolor="#224071">儲存格 2</td>
</tr>
</table>
缺點: 混雜結構與表現、無法復用、維護困難、不支援漸層/透明度/動畫、違反關注點分離原則。
<style>
td.cell-pink { background-color: #e91e6f; }
td.cell-blue { background-color: #224071; }
td.cell-red { background-color: #f12339; }
td.cell-green { background-color: #1ea27e; }
</style>
<table>
<tr>
<td class="cell-pink">01</td>
<td class="cell-blue">02</td>
<td class="cell-red">03</td>
<td class="cell-green">04</td>
</tr>
</table>
:root {
--color-primary: #e91e6f;
--color-secondary: #224071;
--color-accent: #f12339;
--color-success: #1ea27e;
}
td[style*="--bg"] { /* 屬性選擇器示意,實際建議用 class */ }
.cell-primary { background-color: var(--color-primary); }
.cell-secondary { background-color: var(--color-secondary); }
.gradient-cell {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white; /* 確保文字對比度 */
}
.profit-positive { background-color: #d4edda; color: #155724; }
.profit-negative { background-color: #f8d7da; color: #721c24; }
.profit-zero { background-color: #fff3cd; color: #856404; }
JS 邏輯:根據數值正負添加對應 class。
tbody tr:nth-child(even) { background-color: #f8f9fa; }
tbody tr:nth-child(odd) { background-color: #ffffff; }
tbody tr:hover { background-color: #e2e6ea; }
thead th { background-color: #343a40; color: white; position: sticky; top: 0; z-index: 1; }
<colgroup>
<col style="background-color: #f0f8ff;"> <!-- 第一欄淡藍 -->
<col span="2">
<col style="background-color: #fff8e1;"> <!-- 最後一欄淡黃 -->
</colgroup>
背景色與前景文字色必須符合 WCAG 2.1 AA 級:
驗證工具: WebAIM Contrast Checker、瀏覽器開發者工具 Elements 面板顏色選擇器旁的對比度指示器。
| 語義 | 建議色系 | 用途範例 |
|---|---|---|
| 成功/正數/通過 | 綠色系 | 盈利、庫存充足、驗證通過 |
| 警告/待處理 | 黃/橙色系 | 庫存預警、待審核、逾期提醒 |
| 危險/負數/失敗 | 紅色系 | 虧損、缺貨、錯誤、刪除操作 |
| 資訊/中性/次要 | 藍/灰色系 | 一般資訊、停用狀態、輔助說明 |
避免單純用色彩傳達資訊,應配合圖示、文字說明,確保色盲使用者也能理解。
@media print {
td, th {
background-color: transparent !important; /* 節省墨水 */
color: #000 !important;
-webkit-print-color-adjust: exact; /* 強制列印背景 (謹慎用) */
print-color-adjust: exact;
}
}
bgcolor,全面採用 CSS background-color / background。nth-child、<col> 管理樣式。從屬性思維轉向樣式類別思維,是邁向現代前端開發的關鍵一步。