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 属性设置为 dark,就会应用深色模式工具类

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");

同样,你可以随意管理它,甚至可以将首选项存储在数据库中的服务器端并在服务器上呈现类 — 这完全取决于你。

版权所有 © 2025 Tailwind Labs Inc.·商标政策