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

无法在Create Next App中关闭/移除深色模式

问题描述

之前使用create-next-app创建Next.js应用时,生成的「Welcome to Next.js」初始页面默认都是浅色主题;但本次创建的应用会自动跟随系统偏好启用深色模式,希望在不修改系统设置的前提下将应用固定为浅色主题。

附当前项目的package.json内容:

{
  "name": "next-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "12.2.3",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "devDependencies": {
    "eslint": "8.20.0",
    "eslint-config-next": "12.2.3"
  }
}
解决方案

Next.js 12.2.3的默认模板通过CSS媒体查询prefers-color-scheme实现跟随系统主题切换,以下两种方法可固定为浅色主题:

方法一:修改全局CSS文件

项目根目录下的styles/globals.css是全局样式入口,直接覆盖主题变量并移除深色模式的媒体查询:

:root {
  --background: #ffffff;
  --foreground: #171717;
  --card: #ffffff;
  --card-foreground: #171717;
  --popover: #ffffff;
  --popover-foreground: #171717;
  --primary: #2563eb;
  --primary-foreground: #ffffff;
  --secondary: #f3f4f6;
  --secondary-foreground: #171717;
  --muted: #f3f4f6;
  --muted-foreground: #6b7280;
  --accent: #f3f4f6;
  --accent-foreground: #171717;
  --destructive: #ef4444;
  --destructive-foreground: #ffffff;
  --border: #e5e7eb;
  --input: #e5e7eb;
  --ring: #2563eb;
}

/* 删除或注释掉以下深色模式的媒体查询块 */
/* @media (prefers-color-scheme: dark) {
  :root {
    --background: #0a0a0a;
    --foreground: #ededed;
    --card: #1a1a1a;
    --card-foreground: #ededed;
    --popover: #1a1a1a;
    --popover-foreground: #ededed;
    --primary: #3b82f6;
    --primary-foreground: #ffffff;
    --secondary: #262626;
    --secondary-foreground: #ededed;
    --muted: #262626;
    --muted-foreground: #9ca3af;
    --accent: #262626;
    --accent-foreground: #ededed;
    --destructive: #dc2626;
    --destructive-foreground: #ffffff;
    --border: #262626;
    --input: #262626;
    --ring: #3b82f6;
  }
} */

方法二:通过代码强制设置浅色模式

在pages/_app.js中添加逻辑,强制页面使用浅色模式:

import '../styles/globals.css';
import { useEffect } from 'react';

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    // 移除可能存在的dark类
    document.documentElement.classList.remove('dark');
    // 强制浏览器使用浅色配色方案
    document.documentElement.style.setProperty('color-scheme', 'light');
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp;

也可以在pages/_document.js中直接配置HTML根元素的配色方案:

import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  render() {
    return (
      <Html lang="en" style={{ colorScheme: 'light' }}>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:16:38