如何在 Next.js 中使用 Tailwind CSS 进行样式设计?

7 阅读2分钟

Next.js 中使用 Tailwind CSS 完整教程(最简单、最实用)

我给你一套零门槛、可直接用的 Tailwind CSS 使用方法,完全适配最新版 Next.js(App Router / Pages Router 都支持)。


一、最快安装方式(推荐)

创建 Next.js 项目时直接勾选 Tailwind,自动配置好,不用手动改文件:

npx create-next-app@latest my-project

安装时选择:

  • ✅ Tailwind CSS
  • ✅ TypeScript / ESLint 随意

安装完成后,你什么都不用配,直接就能写样式!


二、手动配置(已有项目)

如果你的 Next.js 项目还没装 Tailwind,执行这 3 条命令:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

然后打开 ​​tailwind.config.js​​ 把路径配好(复制即可):

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}", // 适配 App Router
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};

最后在全局 CSS(通常是 ​​app/globals.css​​)顶部加入:

@tailwind base;
@tailwind components;
@tailwind utilities;

配置完成


三、最核心:怎么写样式?(直接复制示例)

Tailwind 是直接在 className 里写工具类,不用写 CSS 文件。

1. 基础样式

export default function Home() {
  return (
    // 文字居中 + 内边距 + 最大宽度 + 居中
    <div className="text-center p-8 max-w-3xl mx-auto">
      <h1 className="text-3xl font-bold text-blue-600">你好 Tailwind</h1>
      <p className="mt-4 text-gray-600">Next.js + Tailwind 超级简单</p>
    </div>
  );
}

2. 按钮样式

<button className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700">
  点击按钮
</button>

3. 卡片样式

<div className="border p-6 rounded-xl shadow-md hover:shadow-lg">
  <h2 className="text-xl font-semibold">卡片标题</h2>
  <p className="text-gray-500 mt-2">这是一段卡片内容</p>
</div>

4. 响应式(移动端适配)

<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
  <div>卡片1</div>
  <div>卡片2</div>
  <div>卡片3</div>
</div>
  • ​md:​​ ≥768px
  • ​lg:​​ ≥1024px
    Tailwind 自动适配手机/平板/电脑

四、最常用的 Tailwind 类(背会就能做网站)

布局

  • ​mx-auto​​ 水平居中
  • ​flex​​ 弹性布局
  • ​grid​​ 网格布局
  • ​p-4​​ 内边距
  • ​m-4​​ 外边距
  • ​container​​ 内容容器

文字

  • ​text-xl​​ 文字大小
  • ​font-bold​​ 加粗
  • ​text-center​​ 居中
  • ​text-blue-600​​ 文字颜色

背景/边框

  • ​bg-blue-500​​ 背景色
  • ​rounded-lg​​ 圆角
  • ​shadow-md​​ 阴影
  • ​border​​ 边框

交互

  • ​hover:bg-blue-600​​ 鼠标悬浮
  • ​active:scale-95​​ 点击缩小
  • ​transition-all​​ 平滑动画

五、高级用法(实用但简单)

1. 自定义颜色(tailwind.config.js)

theme: {
  extend: {
    colors: {
      mycolor: '#165DFF', // 自定义主色
    },
  },
}

使用:

className="text-mycolor bg-mycolor"

2. 提取公共样式(避免重复)

@layer components {
  .btn {
    @apply bg-blue-600 text-white px-6 py-2 rounded-lg;
  }
}

使用:

<button className="btn">按钮</button>

3. 支持暗色模式

// tailwind.config.js
darkMode: "class",

使用:

<div className="bg-white dark:bg-gray-900 text-black dark:text-white">
  自动适配深色模式
</div>

六、VS Code 必备插件(开发效率翻倍)

安装:Tailwind CSS IntelliSense
功能:自动提示、自动补全、语法高亮


总结(超级好记)

  1. 创建项目时直接勾选 Tailwind,不用任何配置
  2. 样式直接写在 className 里
  3. 常用类:​​text-*​​ ​​bg-*​​ ​​p-*​​ ​​m-*​​ ​​rounded​​ ​​shadow​​ ​​flex​​ ​​grid​
  4. 响应式:​​md:​​ ​​lg:​
  5. 交互:​​hover:​​ ​​active:​

你只要学会这些,就能做出任何风格的官网、博客、产品站、后台页面!

需要我给你做一套完整的页面模板(导航栏 + 首页 + 页脚 + 响应式)吗?