跳轉到

建立 2025-02-25 更新 2026-09-11

CSS 顏色(Color)

顏色可以寫名稱、十六進位、rgb()hsl(),以及較新的 oklch()color-mix()。文字與背景的對比比色碼格式更重要。

用在哪裡

p { color: #222; }
body { background-color: #f7f7f8; }
.btn { border-color: currentColor; }

currentColor 等於該元素當下的 color,讓邊框、圖示、底線跟著文字走。

寫法比較

寫法 例子 何時用
關鍵字 tomatotransparent 草稿、語意清楚時
Hex #264de4#264de4cc(8 位含透明) 設計稿最常見
rgb() rgb(38 77 228 / 80%) 與透明一起調
hsl() hsl(226 80% 52%) 想調明暗、做色盤
oklch() oklch(55% 0.18 264) 感知較均勻,現代首選之一

現代語法可用空白分隔、用 / 寫透明度,不必再寫 rgba()

.overlay {
  background: rgb(0 0 0 / 45%);
}

HSL 怎麼讀

  • H 色相:0 紅、120 綠、240 藍
  • S 飽和:0% 灰、100% 純色
  • L 亮度:0% 黑、100% 白
:root {
  --brand-h: 226;
  --brand: hsl(var(--brand-h) 80% 52%);
  --brand-soft: hsl(var(--brand-h) 80% 96%);
}

透明度

做法 影響
rgb(... / 50%) 只有這個顏色半透明
opacity: 0.5 整個元素含子元素都淡,含子文字
color-mix 跟另一色(含 transparent)混合

子元素不要跟著淡時,用顏色的 alpha,不要用 opacity

color-mix() 與主題

:root {
  --text: #1a1a1a;
  --muted: color-mix(in srgb, var(--text) 64%, white);
}

.btn:hover {
  background: color-mix(in srgb, var(--brand) 88%, black);
}

深色模式可搭配 color-scheme 與媒體條件,見 媒體查詢變數

對比與無障礙

  • 正文與背景對比建議達到 WCAG AA(約 4.5:1)
  • 灰字在白底很容易不合格,用開發者工具或對比檢查器驗證
  • 不要只靠紅色/綠色傳達對錯,請加上圖示或文字
.error { color: #b00020; }
.error::before { content: "⚠ "; }

總結

  • 專案裡把品牌色放進 CSS 變數,元件只引用變數。
  • 新碼可用 rgb(r g b / a)color-mix()
  • opacity 影響整棵子樹;平面半透明請寫在顏色上。

背景圖與漸層見 背景