rgba(red, green, blue, alpha)
| 參數 | 取值範圍 | 說明 |
|---|---|---|
| Red / Green / Blue | 0~255(整數)或 0%~100% | 三原色強度 |
| Alpha | 0~1(小數) | 透明度:0 完全透明,1 完全不透明 |
/***** 50% 透明白色文字 *****/
.text-half-white {
color: rgba(255, 255, 255, 0.5);
}
/***** 純紅色背景(Alpha=1) *****/
.bg-red {
background-color: rgba(255, 0, 0, 1);
}
/***** 百分比寫法 *****/
.bg-red-pct {
background-color: rgba(100%, 0%, 0%, 1);
}
/***** 50% 透明黃色 *****/
.text-half-yellow {
color: rgba(255, 242, 0, 0.5);
}
| 格式 | 透明度支援 | 瀏覽器支援 | 適用場景 |
|---|---|---|---|
| #RRGGBB | ❌ | 全瀏覽器 | 不透明色彩 |
| #RRGGBBAA | ✅ (8 位十六進制) | 現代瀏覽器 | 現代專案簡寫 |
| rgb() | ❌ | 全瀏覽器 | 不透明,語意清晰 |
| rgba() | ✅ | IE9+、全現代 | 需要透明度的場景 |
百分比 = (整數值 ÷ 255) × 100%
/* 例:rgba(255, 242, 0, 0.5) */
Red: (255/255) × 100% = 100%
Green: (242/255) × 100% ≈ 94.9%
Blue: (0/255) × 100% = 0%
→ rgba(100%, 94.9%, 0%, 0.5)
整數 = round(百分比值 × 255)
/* 例:rgba(100%, 64.7%, 0%, 1) */
Red: 100% × 255 = 255
Green: 64.7% × 255 ≈ 165
Blue: 0% × 255 = 0
→ rgba(255, 165, 0, 1)
.hero {
background-image: url(banner.jpg);
position: relative;
}
.hero::before {
content: "";
position: absolute; inset: 0;
background: rgba(0, 0, 0, 0.4); /* 深色遮罩提升文字可讀性 */
z-index: 1;
}
.hero-content {
position: relative;
z-index: 2;
color: white;
}
.btn-primary {
background: rgba(52, 152, 219, 1);
transition: background 0.2s;
}
.btn-primary:hover {
background: rgba(52, 152, 219, 0.85); /* 輕微透明表示 hover */
}
.btn-primary:active {
background: rgba(52, 152, 219, 1); /* 按下恢復不透明 */
}
.text-glow {
text-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
}
.border-subtle {
border: 1px solid rgba(0, 0, 0, 0.1); /* 極淡分割線 */
}
.gradient-overlay {
background: linear-gradient(
to bottom,
rgba(0,0,0,0) 0%,
rgba(0,0,0,0.7) 100%
);
}
.fallback-example {
background: rgb(200, 54, 54); /* IE8 顯示不透明版 */
background: rgba(200, 54, 54, 0.5); /* 現代瀏覽器覆蓋透明版 */
}
或使用 PostCSS 插件 自動生成 fallback。
.modern-rgba {
background: #ff000080; /* 紅色 50% 透明 = rgba(255,0,0,0.5) */
/* AA = 170 = 0.67 透明度 */
}
支援:Chrome 62+, Firefox 49+, Safari 9.1+, Edge 79+。新專案可直接使用,更簡潔。
RGBA 是 CSS 色彩系統中實現透明度的標準方式。掌握「整數↔百分比互轉」、「降級寫法」、「現代 8 位十六進制」三大技能,即可在任何專案中靈活運用透明色彩,構建層次豐富的視覺介面。