1. 核心概念(Core Concepts)
  2. 深色模式(Dark mode)

核心概念(Core Concepts)

深色模式(Dark mode)

使用變體為你的網站設定深色模式樣式。

概述(Overview)

隨著深色模式成為許多作業系統的一流功能,為網站設計一個深色版本來配合預設設計變得越來越常見。

為了讓這件事盡可能簡單,Tailwind 提供了 dark 變體,讓你可以在深色模式啟用時為網站設定不同的樣式:

Light mode

Writes upside-down

The Zero Gravity Pen can be used to write in any orientation, including upside-down. It even works in outer space.

Dark mode

Writes upside-down

The Zero Gravity Pen can be used to write in any orientation, including upside-down. It even works in outer space.

<div class="bg-white dark:bg-gray-800 rounded-lg px-6 py-8 ring shadow-xl ring-gray-900/5">  <div>    <span class="inline-flex items-center justify-center rounded-md bg-indigo-500 p-2 shadow-lg">      <svg class="h-6 w-6 stroke-white" ...>        <!-- ... -->      </svg>    </span>  </div>  <h3 class="text-gray-900 dark:text-white mt-5 text-base font-medium tracking-tight ">Writes upside-down</h3>  <p class="text-gray-500 dark:text-gray-400 mt-2 text-sm ">    The Zero Gravity Pen can be used to write in any orientation, including upside-down. It even works in outer space.  </p></div>

預設情況下,這會使用 prefers-color-scheme CSS 媒體功能,但你也可以透過覆寫 dark 變體來建構支援手動切換深色模式的網站。

手動切換深色模式(Toggling dark mode manually)

如果你希望深色主題由 CSS 選擇器驅動,而不是 prefers-color-scheme 媒體查詢,請覆寫 dark 變體以使用你的自訂選擇器:

app.css
@import "tailwindcss";@custom-variant dark (&:where(.dark, .dark *));

現在,dark:* 通用類別將不再基於 prefers-color-scheme 套用,而是在 HTML 樹狀結構中較早出現 dark 類別時套用:

HTML
<html class="dark">  <body>    <div class="bg-white dark:bg-black">      <!-- ... -->    </div>  </body></html>

如何將 dark 類別添加到 html 元素完全取決於你,但常見的做法是使用一段 JavaScript 來更新 class 屬性,並將偏好同步到 localStorage 之類的地方。

使用 data 屬性(Using a data attribute)

若要使用 data 屬性而不是類別來啟用深色模式,只需使用屬性選擇器來覆寫 dark 變體即可:

app.css
@import "tailwindcss";@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));

現在,只要樹狀結構中的某處將 data-theme 屬性設定為 dark,深色模式通用類別就會被套用:

HTML
<html data-theme="dark">  <body>    <div class="bg-white dark:bg-black">      <!-- ... -->    </div>  </body></html>

支援系統主題(With system theme support)

若要建構支援淺色模式、深色模式和系統主題的三向主題切換,請使用自訂深色模式選擇器和 window.matchMedia() API 來偵測系統主題,並在需要時更新 html 元素。

以下是一個簡單的範例,展示如何支援淺色模式、深色模式,以及遵循作業系統偏好:

spaghetti.js
// 在頁面載入或切換主題時,最好在 `head` 中內嵌執行以避免 FOUCdocument.documentElement.classList.toggle(  "dark",  localStorage.theme === "dark" ||    (!("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches),);// 當使用者明確選擇淺色模式時localStorage.theme = "light";// 當使用者明確選擇深色模式時localStorage.theme = "dark";// 當使用者明確選擇遵循作業系統偏好時localStorage.removeItem("theme");

同樣地,你可以用任何你喜歡的方式來管理這件事,甚至可以在伺服器端將偏好儲存在資料庫中,並在伺服器上渲染該類別——完全取決於你。

Copyright © 2026 Tailwind Labs Inc.·商標政策(Brand)