RGB 是**加色模型**(Additive Color Model),透過紅(R)、綠(G)、藍(B)三原色光以不同強度疊加,合成百萬種顏色。
/***** 每通道 0~255 *****/
.pure-blue { color: rgb(0, 0, 255); }
.pure-red { color: rgb(255, 0, 0); }
.magenta { color: rgb(255, 0, 255); } /* 紅+藍 */
.yellow { color: rgb(255, 255, 0); } /* 紅+綠 */
.cyan { color: rgb(0, 255, 255); } /* 綠+藍 */
.white { color: rgb(255, 255, 255); }
.black { color: rgb(0, 0, 0); }
/***** 每通道 0%~100% *****/
.pure-blue-pct { color: rgb(0%, 0%, 100%); }
.gray-50 { color: rgb(50%, 50%, 50%); } /* 中灰 */
兩種語法**完全等價**,瀏覽器內部統一換算為 0~255 整數處理。
/***** CSS Color Level 4 新語法(支援空格分隔 + 斜線透明度) *****/
.modern-rgb {
color: rgb(255 0 0); /* 等同 rgb(255, 0, 0) */
color: rgb(100% 0% 0%); /* 百分比 */
color: rgb(255 0 0 / 0.5); /* 帶 50% 透明度,替代 rgba() */
color: rgb(100% 0% 0% / 50%); /* 百分比透明度 */
}
支援:Chrome 65+, Firefox 52+, Safari 12.1+, Edge 79+。新專案推薦使用此語法,統一 rgb/rgba。
:root {
--hue-primary: 210; /* 藍色系色相 */
}
.btn-primary {
background: hsl(var(--hue-primary), 80%, 50%);
}
.btn-primary:hover {
background: hsl(var(--hue-primary), 80%, 40%);
}
/* 配合 HSL 更直觀調整明度/飽和度,但 RGB 仍是基礎 */
:root {
--color-brand-r: 52;
--color-brand-g: 152;
--color-brand-b: 219;
}
.themeable {
background: rgb(var(--color-brand-r), var(--color-brand-g), var(--color-brand-b));
border-color: rgb(
calc(var(--color-brand-r) - 20),
calc(var(--color-brand-g) - 20),
calc(var(--color-brand-b) - 20)
);
}
/* JS 切換主題 */
document.documentElement.style.setProperty('--color-brand-r', '231');
document.documentElement.style.setProperty('--color-brand-g', '76');
document.documentElement.style.setProperty('--color-brand-b', '60');
使用 Color Thief 等庫從圖片提取主色調 RGB,動態套用至介面元素。
| 色彩空間 | 用途 | CSS 支援 |
|---|---|---|
| sRGB | Web 標準色彩空間,RGB 即指 sRGB | 全支援 |
| Display-P3 | 廣色域(蘋果裝置、高端顯示器) | color: color(display-p3 1 0 0) |
| Rec.2020 | 超廣色域(8K/ HDR 內容) | color: color(rec2020 1 0 0) |
| HSL/HWB/LCH/LAB | 更符合人類直覺的色彩模型 | CSS Color Level 4 現代瀏覽器支援 |
RGB 值可直接用於計算 WCAG 對比度:
function getLuminance(r, g, b) {
const srgb = [r, g, b].map(v => {
v /= 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return 0.2126 * srgb[0] + 0.7152 * srgb[1] + 0.0722 * srgb[2];
}
function contrastRatio(rgb1, rgb2) {
const l1 = getLuminance(...rgb1);
const l2 = getLuminance(...rgb2);
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
}
// AA 級需 4.5:1,AAA 級需 7:1
RGB 是 Web 色彩的基石。掌握「整數/百分比/現代語法」三種寫法、理解加色混合原理、善用 CSS 變數實現動態主題、重視無障礙對比度,即能駕馭色彩系統,打造視覺一致且可維護的介面。