核心概念
使用变体在暗黑模式下设置网站样式。
现在暗黑模式已成为许多操作系统的首要功能,设计网站的暗黑版本以配合默认设计变得越来越普遍。
为了尽可能简化此过程,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 媒体功能,但您也可以构建支持手动切换暗黑模式的站点,方法是覆盖 dark 变体。
如果您希望您的暗黑主题由 CSS 选择器而不是 prefers-color-scheme
媒体查询驱动,请覆盖 dark
变体以使用您的自定义选择器
@import "tailwindcss";@custom-variant dark (&:where(.dark, .dark *));
现在,dark:*
实用程序不再基于 prefers-color-scheme
应用,而是每当 HTML 树中较早位置存在 dark
类时,它们都将被应用
<html class="dark"> <body> <div class="bg-white dark:bg-black"> <!-- ... --> </div> </body></html>
如何在 html
元素中添加 dark
类取决于您,但一种常见的方法是使用少量 JavaScript 来更新 class
属性并将该首选项同步到 localStorage
等位置。
要使用数据属性而不是类来激活暗黑模式,只需使用属性选择器覆盖 dark
变体即可
@import "tailwindcss";@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
现在,每当 data-theme
属性在树中的某个位置设置为 dark
时,暗黑模式实用程序都将被应用
<html data-theme="dark"> <body> <div class="bg-white dark:bg-black"> <!-- ... --> </div> </body></html>
要构建支持亮色模式、暗黑模式和系统主题的三向主题切换,请使用自定义暗黑模式选择器和 window.matchMedia()
API 来检测系统主题并在需要时更新 html
元素。
这是一个简单的示例,说明如何支持亮色模式、暗黑模式以及尊重操作系统首选项
// On page load or when changing themes, best to add inline in `head` to avoid FOUCdocument.documentElement.classList.toggle( "dark", localStorage.theme === "dark" || (!("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches),);// Whenever the user explicitly chooses light modelocalStorage.theme = "light";// Whenever the user explicitly chooses dark modelocalStorage.theme = "dark";// Whenever the user explicitly chooses to respect the OS preferencelocalStorage.removeItem("theme");
同样,您可以随意管理此操作,甚至可以将首选项服务器端存储在数据库中并在服务器上呈现类 - 这完全取决于您。