Try   HackMD

【Tailwind CSS】夜間模式 Dark Mode

目前在許多作業系統夜間模式都已經是必備的功能了,Tailwind 也有提供開發夜間模式的功能

使用 dark variant 來讓你的網站樣式根據夜間模式來做改變吧

image
圖片來源: Tailwind 官網

使用:

bg-white
dark:bg-slate-800

Tailwind預設會使用 prefers-color-scheme,這個模式會讓你的網站根據使用者在他自己的作業系統裡面的設定來選擇呈現日間或夜間模式

手動開啟或關閉夜間模式

如果你想要手動切換夜間模式而不是根據瀏覽器預設來顯示可以使用 selector 而不是使用 media

/** @type {import('tailwindcss').Config} */ module.exports = { darkMode: 'selector', // ... }

3.4.1版本以前要使用 class 而不是 selector

使用了之後自己加上 dark class 就會顯示 dark 的 css class

<!-- Dark mode not enabled --> <html> <body> <!-- Will be white --> <div class="bg-white dark:bg-black"> <!-- ... --> </div> </body> </html> <!-- Dark mode enabled --> <html class="dark"> <body> <!-- Will be black --> <div class="bg-white dark:bg-black"> <!-- ... --> </div> </body> </html>

改成手動模式你就可以利用 js 來控制夜間模式的開啟與否

如果你有使用到 tailwind 前綴記得前綴也要加上去,例如你使用 tw- 當前綴, dark 也要改成 tw-dark

客制化 Selector

有些框架有他們自己的 dark mode 關鍵字,有時候會自己添加他們自己定義的 dark mode class,你可以自己設定 dark mode 的關鍵字來讓它們符合你所使用的框架的規則

/** @type {import('tailwindcss').Config} */ module.exports = { darkMode: ['selector', '[data-mode="dark"]'], // ... }

同時使用作業系統預設與手動選擇

你可以使用 window.matchMedia() API 來讓你的專案同時可以使用作業系統預設與手動模式

// On page load or when changing themes, best to add inline in `head` to avoid FOUC document.documentElement.classList.toggle( 'dark', localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches) ) // Whenever the user explicitly chooses light mode localStorage.theme = 'light' // Whenever the user explicitly chooses dark mode localStorage.theme = 'dark' // Whenever the user explicitly chooses to respect the OS preference localStorage.removeItem('theme')

補充: FOUC

覆蓋 dark variants

你想把 tailwind 內建的 dark variants 改成你自己的 dark variants 也是可以的

/** @type {import('tailwindcss').Config} */ module.exports = { darkMode: ['variant', '&:not(.light *)'], // ... }

使用多個選擇器

如果你有各種不同的情境來啟用夜間模式,也可以設置多個

/** @type {import('tailwindcss').Config} */ module.exports = { darkMode: ['variant', [ '@media (prefers-color-scheme: dark) { &:not(.light *) }', '&:is(.dark *)', ]], // ... }