Tailwind / Next.js 深色模式自动适配
在 Next.js 项目中使用 Tailwind CSS,可基于系统主题自动适配深色模式。
配置
// tailwind.config.js
module.exports = {
darkMode: 'media',
content: [
'./app/**/*.{ts,tsx}',
'./components/**/*.{ts,tsx}',
],
};
使用
export default function Card() {
return (
<div className="
bg-white text-gray-900
dark:bg-zinc-900 dark:text-gray-100
border border-gray-200 dark:border-zinc-700
rounded-lg p-4
">
Dark Mode Card
</div>
);
}
全局样式(可选)
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
@apply bg-gray-50 text-gray-900
dark:bg-black dark:text-gray-100;
}
特点
- 自动跟随系统主题
- 无脚本依赖
- SSR 友好
- Tailwind 原生支持
兼容性
现代浏览器(Chrome / Edge / Firefox / Safari)