1. 核心概念
  2. 深色模式

核心概念

深色模式

使用變體在深色模式中設定網站樣式。

概述

現在深色模式已成為許多作業系統的一級功能,設計網站的深色版本以搭配預設設計變得越來越普遍。

為了盡可能簡化此過程,Tailwind 包含一個 dark 變體,可讓您在啟用深色模式時以不同方式設定網站樣式

淺色模式

顛倒書寫

零重力筆可以用於以任何方向書寫,包括顛倒。它甚至可以在外太空中使用。

深色模式

顛倒書寫

零重力筆可以用於以任何方向書寫,包括顛倒。它甚至可以在外太空中使用。

<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 媒體功能,但您也可以透過覆寫深色變體來建構支援手動切換深色模式的網站。

手動切換深色模式

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

app.css
@import "tailwindcss";@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 的位置。

使用資料屬性

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

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

現在,當 data-theme 屬性設定為樹狀結構中的某個位置時,將會套用深色模式實用工具

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

具有系統主題支援

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

以下是一個簡單的範例,說明如何支援淺色模式、深色模式,以及尊重作業系統偏好

spaghetti.js
// On page load or when changing themes, best to add inline in `head` to avoid FOUCdocument.documentElement.classList.toggle(  "dark",  localStorage.currentTheme === "dark" ||    (!("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches),);// Whenever the user explicitly chooses light modelocalStorage.currentTheme = "light";// Whenever the user explicitly chooses dark modelocalStorage.currentTheme = "dark";// Whenever the user explicitly chooses to respect the OS preferencelocalStorage.removeItem("theme");

同樣地,您可以根據自己的喜好管理此設定,甚至可以將偏好儲存在伺服器端的資料庫中,並在伺服器上呈現類別 — 完全取決於您。

Copyright © 2025 Tailwind Labs Inc.·商標政策