# 【Tailwind CSS】夜間模式 Dark Mode 目前在許多作業系統夜間模式都已經是必備的功能了,Tailwind 也有提供開發夜間模式的功能 **使用 `dark` variant 來讓你的網站樣式根據夜間模式來做改變吧**  圖片來源: Tailwind 官網 使用: ``` bg-white dark:bg-slate-800 ``` :::info Tailwind預設會使用 `prefers-color-scheme`,這個模式會讓你的網站根據使用者在他自己的作業系統裡面的設定來選擇呈現日間或夜間模式 ::: ## 手動開啟或關閉夜間模式 如果你想要手動切換夜間模式而不是根據瀏覽器預設來顯示可以使用 `selector` 而不是使用 `media` ```js= /** @type {import('tailwindcss').Config} */ module.exports = { darkMode: 'selector', // ... } ``` >3.4.1版本以前要使用 `class` 而不是 `selector` 使用了之後自己加上 `dark` class 就會顯示 dark 的 css class ```html= <!-- 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 來控制夜間模式的開啟與否 :::info 如果你有使用到 [tailwind 前綴](https://tailwindcss.com/docs/configuration#prefix)記得前綴也要加上去,例如你使用 `tw-` 當前綴, `dark` 也要改成 `tw-dark` ::: ## 客制化 Selector 有些框架有他們自己的 dark mode 關鍵字,有時候會自己添加他們自己定義的 dark mode class,你可以自己設定 dark mode 的關鍵字來讓它們符合你所使用的框架的規則 ```js= /** @type {import('tailwindcss').Config} */ module.exports = { darkMode: ['selector', '[data-mode="dark"]'], // ... } ``` ## 同時使用作業系統預設與手動選擇 你可以使用 [`window.matchMedia() API`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) 來讓你的專案同時可以使用作業系統預設與手動模式 ```js= // 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') ``` :::info 補充: [FOUC](https://inbound.technology/fouc-flash-of-unstyled-content-%E7%B6%B2%E9%A0%81%E6%A8%A3%E5%BC%8F%E7%9F%AD%E6%9A%AB%E5%A4%B1%E6%95%88%E6%98%AF%E4%BB%80%E9%BA%BC%EF%BC%9F%E5%8E%9F%E5%9B%A0%E7%82%BA%E4%BD%95%EF%BC%9F/) ::: ## 覆蓋 dark variants 你想把 tailwind 內建的 dark variants 改成你自己的 dark variants 也是可以的 ```js= /** @type {import('tailwindcss').Config} */ module.exports = { darkMode: ['variant', '&:not(.light *)'], // ... } ``` ## 使用多個選擇器 如果你有各種不同的情境來啟用夜間模式,也可以設置多個 ```js= /** @type {import('tailwindcss').Config} */ module.exports = { darkMode: ['variant', [ '@media (prefers-color-scheme: dark) { &:not(.light *) }', '&:is(.dark *)', ]], // ... } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up