完整解釋
白話: token 是有用途名稱的色彩插座;元件插 --surface,不必知道現在是白色還是深藍。
正式說法: CSS custom property 參與 cascade 並以 var() 取值;semantic token name 描述 UI role,而非綁定特定色相或明暗值。
何時使用: 多個元件共用背景、文字、邊框、品牌或 focus 色,並可能換主題時。
修改前後: Before:每張卡各寫 #fff、#17324d。After:元件只引用 semantic tokens,scope 負責提供值。
常見混淆: --blue-500 是 palette token;--brand-action 才描述用途。兩者可分層,但不應把色名冒充用途。
名詞與最小範例
用途型 CSS token Semantic CSS custom property tokens
白話 token 是有用途名稱的色彩插座;元件插 --surface,不必知道現在是白色還是深藍。
正式定義 CSS custom property 參與 cascade 並以 var() 取值;semantic token name 描述 UI role,而非綁定特定色相或明暗值。
何時使用 多個元件共用背景、文字、邊框、品牌或 focus 色,並可能換主題時。
最小範例 :root{--surface:#fff;--text:#17324d}.card{background:var(--surface);color:var(--text)}
驗收證據 runtime before=rgb(255, 255, 255)、after=rgb(217, 238, 243)、property=background-color
常混淆 --blue-500 是 palette token;--brand-action 才描述用途。兩者可分層,但不應把色名冒充用途。
Micro Lab|用途型 CSS token
情境: 首頁十張卡片都直接寫白底,現在品牌希望同時換成淡藍色表面。
起始狀態: 卡片使用 var(--surface),根 scope 提供 #fff;未套 alternate-surface。
執行實驗切換 alternate-surface class,只覆寫 --surface,讀取同一元件的 computed background-color。 執行下方操作,觀察獨立的 DOM 與資料狀態。 依證據欄位重新驗收。
目前主題:用途型 CSS token
執行 Micro Lab 操作
尚未執行;DOM data-state=starter。
預期: runtime 的 background-color 由 rgb(255, 255, 255) 變 rgb(217, 238, 243),元件宣告仍為 background:var(--surface)。
證據: runtime before=rgb(255, 255, 255)、after=rgb(217, 238, 243)、property=background-color
第一個檢查: 在 Styles 確認 background 使用 var(--surface),不是另一個固定色碼。
重設: 重新載入 module,移除 alternate-surface class。
卡住時 症狀: 覆寫 --surface 後卡片背景沒有變。可能原因: 卡片仍使用固定 background-color,或 token 覆寫不在卡片可繼承的 scope。先檢查: 查看卡片 Styles 的 background 來源與 --surface 定義位置。修正: 改為 background:var(--surface),並在卡片自身或祖先 scope 提供 token。
本模組官方來源: MDN|Using CSS custom properties