萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML 文字顏色設定現代指南:CSS color 屬性、單位與無障礙對比度

棄用的 <font> 標籤

<font color="red" size="3" face="Arial"> 在 HTML5 中已移除,瀏覽器雖兼容但不保證未來支援。請改用 CSS。

CSS color 屬性與色彩單位

單位類型語法範例說明
關鍵字color: red; color: transparent;16 基本色 + 131 擴展色名,不透明度無法控制
十六進制color: #ff0000; color: #f00; color: #ff000080; (8 位含 alpha)#RRGGBB、#RGB、#RRGGBBAA、#RGBA
RGB/RGBAcolor: rgb(255,0,0); color: rgba(255,0,0,0.5);0-255 或 0%-100%,alpha 0-1
HSL/HSLAcolor: hsl(0,100%,50%); color: hsla(0,100%,50%,0.5);色相 0-360、飽和度%、亮度%,直覺調色
HWBcolor: hwb(0 0% 0%);色相、白度、黑度 (CSS Color Level 4)
LCH / Labcolor: lch(53.23% 104.55 40.5);感知均勻色彩空間 (CSS Color Level 4)
color() 函數color(display-p3 1 0 0);指定色域 (P3, Rec2020 等)

實戰範例

:root {
  --brand-primary: #2c3e50;
  --brand-accent: #e74c3c;
  --text-main: #333;
  --text-muted: #666;
}
body { color: var(--text-main); }
h1, h2, h3 { color: var(--brand-primary); }
.btn-primary { color: #fff; background: var(--brand-primary); }
.btn-danger { color: #fff; background: var(--brand-accent); }
.text-muted { color: var(--text-muted); }

字體相關屬性速查

屬性用途範例
font-family字體堆疊font-family: "Noto Sans TC", "Microsoft JhengHei", sans-serif;
font-size字號font-size: 1rem; (建議用 rem/em)
font-weight粗細font-weight: 700; (normal=400, bold=700)
font-style斜體font-style: italic;
line-height行高line-height: 1.6; (無單位為倍數)
text-align水平對齊text-align: center;
text-decoration底線/刪除線text-decoration: underline;
text-transform大小寫轉換text-transform: uppercase;
letter-spacing字距letter-spacing: 0.05em;
word-spacing詞距word-spacing: 0.2em;

標題對齊範例(語義化 + CSS)

<h1 class="text-center">主標題置中</h1>
<h2 class="text-right">副標題靠右</h2>

.text-center { text-align: center; }
.text-right  { text-align: right; }

優於 <h1 align="center">(已棄用)。

無障礙對比度檢查

  • 正常文字 (<18pt 或 <14pt bold):對比度 ≥ 4.5:1 (AA) / 7:1 (AAA)。
  • 大號文字 (≥18pt 或 ≥14pt bold):對比度 ≥ 3:1 (AA) / 4.5:1 (AAA)。
  • 工具:WebAIM Contrast Checker、瀏覽器開發者工具 Elements 面板色彩選取器旁的對比度指示。

CSS 變數與主題切換

[data-theme="dark"] {
  --text-main: #e0e0e0;
  --brand-primary: #3498db;
}

搭配 JS 切換 document.documentElement.dataset.theme 實現深色模式。

copyright © 萬盛學電腦網 all rights reserved