表格背景半透明能疊加頁面背景圖/色,營造層次感。本文說明現代 CSS rgba()/hsla()/#RRGGBBAA、opacity 差異、IE 相容濾鏡 filter:Alpha、以及避免內容同步透明的技巧。
| 語法 | 範例 | 瀏覽器支援 | 備註 |
|---|---|---|---|
| rgba() | background: rgba(51, 102, 153, 0.5); | IE9+ | 最常用 |
| hsla() | background: hsla(210, 50%, 40%, 0.5); | IE9+ | 色相直觀調整 |
| #RRGGBBAA | background: #33669980; | 現代瀏覽器 | 8 位元 HEX,Alpha=80(16進位)=128≈50% |
| color-mod() | background: color(var(--c) alpha(50%)); | 實驗性 | CSS Color Level 5 |
table.semi-transparent {
background: rgba(0, 0, 0, 0.3); /* 深色半透明 */
border-collapse: collapse;
}
table.semi-transparent td, table.semi-transparent th {
background: transparent; /* 關鍵:儲存格透明,讓表格背景顯現 */
}
tr.highlight td { background: rgba(255, 255, 0, 0.2); } /* 黃色高亮列 */
td.special { background: hsla(120, 80%, 40%, 0.3); } /* 綠色半透明格 */
thead th {
position: sticky; top: 0; z-index: 1;
background: rgba(255, 255, 255, 0.95); /* 近乎不透明,避免滾動時文字重疊 */
backdrop-filter: blur(4px); /* 毛玻璃效果,現代瀏覽器支援 */
}
<!-- 錯誤示範 -->
<table style="opacity: 0.5;"> <!-- 文字、圖片、邊框全變半透明 -->
</table>
<!-- 正確:只讓背景透明 -->
<table style="background: rgba(255,255,255,0.5);">
<tr><td>文字保持不透明</td></tr>
</table>
原則:opacity 作用於**整個元素及子孫**;rgba/hsla/#RRGGBBAA 僅作用於**背景層**。
<td style="background-color:#336699; filter:Alpha(opacity=50);">內容</td>
filter:Alpha(opacity=50):0~100,50 代表 50% 不透明<style>
.page { background: url('bg-pattern.jpg') center/cover fixed; min-height:100vh; padding:2rem; }
.table-glass {
border-collapse: collapse; width:100%; max-width:800px; margin:0 auto;
background: rgba(255,255,255,0.85); /* 白色 85% 不透明 */
border-radius: 12px; overflow: hidden;
box-shadow: 0 8px 32px rgba(0,0,0,0.1);
backdrop-filter: blur(8px); /* 毛玻璃,Safari 需 -webkit-backdrop-filter */
}
.table-glass th, .table-glass td {
border: 1px solid rgba(0,0,0,0.08);
padding: 14px 16px;
background: transparent; /* 關鍵 */
}
.table-glass thead th {
background: rgba(0, 51, 102, 0.9); color: #fff;
position: sticky; top: 0; z-index: 1;
}
.table-glass tbody tr:hover td { background: rgba(0, 102, 204, 0.05); }
</style>
<div class="page">
<table class="table-glass">
<thead><tr><th>項目</th><th>數值</th></tr></thead>
<tbody>
<tr><td>收入</td><td>$1,234,567</td></tr>
<tr><td>支出</td><td>$789,012</td></tr>
</tbody>
</table>
</div>
text-shadow 增強可讀性.bg-white-10 { background: rgba(255,255,255,0.1); }
.bg-white-20 { background: rgba(255,255,255,0.2); }
.bg-white-50 { background: rgba(255,255,255,0.5); }
.bg-white-80 { background: rgba(255,255,255,0.8); }
.bg-black-10 { background: rgba(0,0,0,0.1); }
.bg-black-30 { background: rgba(0,0,0,0.3); }
.bg-black-50 { background: rgba(0,0,0,0.5); }
.bg-primary-10 { background: rgba(37, 99, 235, 0.1); } /* 藍 */
.bg-success-10 { background: rgba(16, 185, 129, 0.1); } /* 綠 */
.bg-warning-10 { background: rgba(245, 158, 11, 0.1); } /* 黃 */
.bg-danger-10 { background: rgba(239, 68, 68, 0.1); } /* 紅 */
/* 使用 */
<td class="bg-success-10">達成率 102%</td>
掌握 RGBA/HSLA/HEXA 現代語法,拋棄 filter:Alpha 與 opacity 陷阱,配合 backdrop-filter 毛玻璃效果,即可打造層次豐富、無障礙友善、深色模式自適應的半透明表格背景。