You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Next.js中将Tailwind CSS默认深色模式切换为浅色模式?

在Next.js中切换Tailwind CSS默认主题为浅色模式

为什么默认会启用深色模式?

这不是Next.js的默认设置,而是Tailwind CSS本身的默认行为:Tailwind默认采用media深色模式策略,会自动检测用户的系统主题偏好(比如系统设置为深色时,页面自动应用深色样式)。

切换为浅色模式的两种方案

方案1:完全禁用深色模式

如果不需要深色模式功能,可以直接在Tailwind配置中禁用它,页面将始终显示浅色样式:

修改你的Tailwind配置文件如下:

import type { Config } from 'tailwindcss'

const config: Config = {
  content: [
    './src/pages/**/*.{js,ts,jsx,tsx,mdx}',
    './src/components/**/*.{js,ts,jsx,tsx,mdx}',
    './src/app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  // 添加此行禁用深色模式
  darkMode: false,
  theme: {
    extend: {
   
    },
  },
  plugins: [],
  
}
export default config

方案2:保留深色模式能力,但默认显示浅色

如果之后可能需要手动切换主题,可采用class模式,默认不给根元素添加dark类即可保持浅色:

  1. 修改Tailwind配置为类模式:
import type { Config } from 'tailwindcss'

const config: Config = {
  content: [
    './src/pages/**/*.{js,ts,jsx,tsx,mdx}',
    './src/components/**/*.{js,ts,jsx,tsx,mdx}',
    './src/app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  // 切换为class模式
  darkMode: 'class',
  theme: {
    extend: {
   
    },
  },
  plugins: [],
  
}
export default config
  1. 确保根元素(比如app/layout.tsx或pages/_app.tsx)没有添加dark类,示例如下(以App Router的布局文件为例):
// app/layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="zh-CN">
      <body>{children}</body>
    </html>
  )
}

(如果需要切换深色模式,只需给<html>或<body>标签添加dark类即可)

内容的提问来源于stack exchange,提问作者Cherry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:42:42