在 HTML 與 CSS 中設定顏色,有多種表示法。本文完整整理十六進制、RGB/RGBA、HSL/HSLA、命名色彩的語法與用法,並提供實用工具建議。
最常用、瀏覽器支援度最高的格式。
#RRGGBB,如 #ff0000 (紅)、#00ff00 (綠)、#0000ff (藍)。#RGB,當每對字元相同時可縮寫,如 #f00 = #ff0000,#0f0 = #00ff00。#RRGGBBAA,如 #ff000080 (50% 透明紅)。現代瀏覽器支援良好。直接對應光的三原色數值(0-255)。
rgb(255, 0, 0) — 紅色rgba(255, 0, 0, 0.5) — 50% 透明紅色(alpha 0~1)rgb(255 0 0 / 0.5)更符合人類直覺:色相 (0-360°)、飽和度 (0-100%)、亮度 (0-100%)。
hsl(0, 100%, 50%) — 紅色hsla(0, 100%, 50%, 0.5) — 50% 透明紅色hsl(0 100% 50% / 0.5)CSS 定義 140+ 個命名色彩(如 red, blue, tomato, rebeccapurple)。完整清單請參考 MDN Named Colors。雖然方便記憶,但精確控制仍建議用數值格式。
transparent — 完全透明(等同 rgba(0,0,0,0))currentColor — 繼承父元素的 color 值,適用於 border-color, box-shadow, svg fill 等。<style>
.box {
/* 背景色 */
background-color: #1a73e8; /* Hex */
background-color: rgb(26, 115, 232); /* RGB */
background-color: hsl(217, 80%, 51%); /* HSL */
background-color: dodgerblue; /* Named */
/* 文字顏色 */
color: #ffffff;
color: rgb(255 255 255 / 0.9); /* 現代語法含透明度 */
/* 邊框顏色 */
border: 2px solid currentColor; /* 跟隨文字顏色 */
/* 漸層背景(進階) */
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
</style>
--color-primary-500: #1a73e8),透過 CSS 變數統一管理。文字與背景對比度需符合 WCAG 2.1 AA 級:
選擇適合專案的顏色表示法,並建立一致的色彩系統,是打造專業視覺介面的基石。