如何在Tailwind CSS v4中无需dark:前缀定义适配明暗模式的自定义颜色
在Tailwind CSS v4中用CSS变量实现明暗模式自动切换(无需
dark:前缀) 一、全局CSS配置:定义动态颜色变量
在React项目的全局样式文件(比如src/index.css或src/styles/globals.css)中,通过:root和模式标识(推荐用data-theme属性,更灵活)定义亮色/暗色模式对应的CSS变量,同时可兼容系统偏好自动切换:
@tailwind base; @tailwind components; @tailwind utilities; /* 亮色模式默认变量 */ :root { --color-primary: #3b82f6; --color-base: #ffffff; --color-text: #1f2937; } /* 手动切换暗色模式时的变量 */ [data-theme="dark"] { --color-primary: #60a5fa; --color-base: #111827; --color-text: #f3f4f6; } /* 跟随系统偏好自动切换暗色模式 */ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --color-primary: #60a5fa; --color-base: #111827; --color-text: #f3f4f6; } }
二、Tailwind配置:映射CSS变量到自定义颜色
在tailwind.config.ts中,将自定义颜色名称映射到上述CSS变量,并配置暗色模式的触发策略:
import type { Config } from "tailwindcss"; export default { content: ["./src/**/*.{js,jsx,ts,tsx}"], theme: { extend: { colors: { // 直接关联CSS变量,无需重复写颜色值 primary: "var(--color-primary)", baseColor: "var(--color-base)", textColor: "var(--color-text)", }, }, }, // 配置暗色模式触发条件:匹配[data-theme="dark"]属性 darkMode: ["class", '[data-theme="dark"]'], } satisfies Config;
三、React中实现手动模式切换(可选)
如果需要支持用户手动切换明暗模式,可编写一个简单的Hook管理状态:
import { useEffect, useState } from "react"; export function useThemeSwitcher() { // 优先读取本地存储的主题,默认跟随系统 const [theme, setTheme] = useState<string>( localStorage.getItem("theme") || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light") ); useEffect(() => { document.documentElement.setAttribute("data-theme", theme); localStorage.setItem("theme", theme); }, [theme]); const toggleTheme = () => { setTheme(prev => prev === "light" ? "dark" : "light"); }; return { theme, toggleTheme }; }
使用示例:
function ThemeToggle() { const { theme, toggleTheme } = useThemeSwitcher(); return ( <button onClick={toggleTheme} className="bg-primary text-baseColor px-4 py-2 rounded" > 切换到{theme === "light" ? "暗色" : "亮色"}模式 </button> ); }
四、日常使用
现在可以直接使用自定义颜色类,无需添加dark:前缀,颜色会自动跟随模式切换:
function App() { return ( <div className="min-h-screen bg-baseColor text-textColor"> <header className="bg-primary text-baseColor p-4"> <h1 className="text-xl">明暗模式自动切换示例</h1> </header> <main className="p-4"> <p className="mb-4">这段文本和背景色会随模式自动变化</p> <ThemeToggle /> </main> </div> ); }
内容的提问来源于stack exchange,提问作者Mourya Pranay
相关产品推荐
相关产品推荐

