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

如何使用Tailwind CSS修改React JS(Next JS)项目所有页面的默认背景色

你参考的浅灰色示例:
浅灰色背景参考图

可以直接全局配置,不需要逐页修改,根据你使用的Next.js路由模式对应操作即可:

步骤1:(可选)自定义目标浅灰色到Tailwind配置

如果你要用的浅灰色不是Tailwind内置色值,可以先修改tailwind.config.js(或.ts)文件,添加自定义色值:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {
      colors: {
        // 这里的色值可以替换为你参考图对应的实际浅灰色色值
        'custom-light-gray': '#f2f2f2'
      }
    }
  },
  plugins: []
}

如果你用Tailwind自带的浅灰色(比如bg-gray-50、bg-gray-100),可以跳过这一步。

步骤2:全局配置背景色

场景1:使用Next.js App Router(v13+ 默认路由模式)

直接修改根布局文件app/layout.tsx(或.jsx),给<body>标签添加背景色类即可,所有页面都会继承该样式:

// app/layout.tsx
import './globals.css'
import type { Metadata } from 'next'

export const metadata: Metadata = {
  title: '你的应用名称',
  description: '你的应用描述',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="zh-CN">
      {/* 添加min-h-screen是为了避免内容不足一屏时背景色显示不全 */}
      <body className="bg-custom-light-gray min-h-screen">{children}</body>
    </html>
  )
}

场景2:使用Next.js Pages Router

修改根目录下的pages/_app.tsx(或.jsx)文件,给外层容器添加背景色类:

// pages/_app.tsx
import type { AppProps } from 'next/app'
import '../styles/globals.css'

export default function App({ Component, pageProps }: AppProps) {
  return (
    <div className="bg-custom-light-gray min-h-screen">
      <Component {...pageProps} />
    </div>
  )
}

如果文件里已经有外层容器,直接给现有容器加背景色类即可。

补充说明

如果后续有个别页面需要使用不同的背景色,直接在对应页面的最外层容器添加其他背景色类,即可覆盖全局配置的样式。

内容的提问来源于stack exchange,提问作者I'm Sunil3

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:57:00