表格背景色能強化資料分組、提升閱讀辨識度。本文涵蓋舊版 bgcolor、background 屬性,並完整示範 CSS background-color、background-image、漸層、透明度(RGBA/HSLA)等現代寫法。
| 屬性 | 值格式 | 範例 |
|---|---|---|
| bgcolor | 顏色關鍵字 / #RRGGBB / rgb() | bgcolor="#000000" bgcolor="black" |
| background | 圖片 URL(相對/絕對路徑) | background="clouds.gif" |
缺點:無法控制圖片重複、定位、漸層、透明度;HTML5 已棄用。
/* 整張表格 */
table { background-color: #F5F5F5; }
/* 單一列 */
tr:nth-child(even) { background-color: rgba(0, 128, 0, 0.1); } /* 綠色 10% 透明 */
/* 單一儲存格 */
td.highlight { background-color: #FFF3CD; }
table {
background-image: url('pattern.png');
background-repeat: repeat; /* repeat | no-repeat | repeat-x | repeat-y */
background-position: center; /* 關鍵字或座標 */
background-size: cover; /* cover | contain | 具體尺寸 */
background-attachment: scroll; /* scroll | fixed */
}
/* 線性漸層:表頭深色 → 內容淡色 */
thead { background: linear-gradient(180deg, #2C3E50, #1A252F); color:#fff; }
tbody tr:nth-child(odd) { background: linear-gradient(180deg, #FAFAFA, #F0F0F0); }
tbody tr:nth-child(even) { background: linear-gradient(180deg, #FFF, #FAFAFA); }
CSS 依據選擇器權重與層疊順序決定最終顏色:
table { background: #EEE; } /* 第 1 層:整張表格 */
tbody { background: #FFF; } /* 第 2 層:主體區塊 */
tr { background: transparent; } /* 第 3 層:列 */
td, th { background: transparent; } /* 第 4 層:儲存格(最上層) */
td.special { background: #FFEB3B; } /* 第 5 層:特定類別覆蓋 */
善用 transparent 讓上層透出下層色彩,構建豐富視覺層次。
background: rgba(255, 0, 0, 0.3);(紅色 30% 不透明)background: hsla(120, 100%, 50%, 0.2);(綠色 20% 不透明)td { opacity: 0.5; }(會連同文字一起變透明,慎用)background: linear-gradient(rgba(0,0,0,0.4), rgba(0,0,0,0.4)), url(bg.jpg);<style>
.data-table { border-collapse:collapse; width:100%; font-family:sans-serif; }
.data-table th { background:linear-gradient(180deg,#2C3E50,#1A252F); color:#fff; padding:12px; }
.data-table td { padding:10px; border:1px solid #DDD; }
.data-table tbody tr:nth-child(odd) { background:#FAFAFA; }
.data-table tbody tr:nth-child(even) { background:#FFF; }
.data-table tbody tr:hover td { background:#E8F4FD; }
.data-table td.total { background:linear-gradient(180deg,#FFF3CD,#FFE082); font-weight:bold; }
</style>
<table class="data-table">
<thead><tr><th>項目</th><th>金額</th></tr></thead>
<tbody>
<tr><td>產品 A</td><td>$1,200</td></tr>
<tr><td>產品 B</td><td>$3,500</td></tr>
<tr><td class="total">合計</td><td class="total">$4,700</td></tr>
</tbody>
</table>
結語:拋棄 bgcolor/background,擁抱 CSS 背景模組,你將獲得像素級控制力、響應式彈性與無障礙友善的表格視覺體驗。