Tailwindcss 4 的 Dark Mode 設定與 v3 相比,設定方式有明顯的調整。這邊筆記下靜態設定和從遠端 api 獲得 CSS 相關設定值兩種方式來搭配使用。
內容
1. 將 dark: 的行為從預設基於 prefers-color-scheme (系統偏好設定),改為基於 .dark 父層類別的存在來運作。這樣可以讓開發者更靈活地控制深色模式,
例如透過 JavaScript 動態切換 .dark 類別來啟用或停用深色模式。 */
1 |
@custom-variant dark (&:where(.dark, .dark *)); |
靜態設定
用 @theme 將變數包裝,然後搭配 @layer 並下變數來建立對應的數值
1 2 3 4 5 6 7 8 9 |
@theme { --color-pink: #eb6bd8; } @layer base { @variant dark { --color-pink: #8e0d7a; } } |
動態設定
在 document 的 head 內,加入一個 <style> 標籤,內容填入 :root 和 html.dark 的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
export function useThemeCssVars() { const setCssVars = ({ themeId = 'theme-vars', lightVars, darkVars, }: { themeId?: string lightVars: Record<string, string | undefined> darkVars?: Record<string, string | undefined> }) => { if (!document) return // no document in ssr const toCssVars = (vars: Record<string, string | undefined>) => Object.entries(vars) .filter(([, val]) => val) .map(([key, val]) => ` --${key}: #${val};`) .join('\n') let styleEl = document.getElementById(themeId) as HTMLStyleElement | null if (!styleEl) { styleEl = document.createElement('style') styleEl.id = themeId document.head.appendChild(styleEl) } const lightCss = toCssVars(lightVars) const darkCss = darkVars ? toCssVars(darkVars) : '' styleEl.innerHTML = `:root {${lightCss}} \n html.dark {${darkCss}}`.trim() } return { setCssVars, } } |
使用時,要注意需在 Client 端執行
1 2 3 4 5 6 7 8 9 10 11 12 |
setCssVars({ lightVars: { 'layout-color': 'F4F4F4', 'text-color': '333333', 'btn-color': 'FF9900', }, darkVars: { 'layout-color': '1A1A1A', 'text-color': 'CCCCCC', 'btn-color': 'FF6600', }, }) |