Next.js CSS 樣式與 Tailwind CSS
Next.js 支援多種設計樣式的方式,從傳統的 CSS 到現代的 Utility-first 框架。無論你喜歡哪種方式,Next.js 都提供了內建的優化支援。
Tailwind CSS (強力推薦)
Tailwind CSS 是 Next.js 官方首選的樣式解決方案。它讓你直接在 HTML Class 中撰寫樣式,極大地提升了開發效率並減少了 CSS 檔案體積。
1. 初始化設定
如果你在建立專案時選擇了 Tailwind CSS,tailwind.config.ts 會自動生成。
// tailwind.config.ts
import type { Config } from 'tailwindcss';
const config: Config = {
content: [
'./app/**/*.{js,ts,jsx,tsx,mdx}', // 確保掃描 app 目錄
'./components/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {},
},
plugins: [],
};
export default config;
2. 在全域引入
你需要在 app/globals.css 中載入 Tailwind 的基礎指令:
/* app/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
並在 app/layout.tsx 中匯入該檔案:
import './globals.css';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
);
}
3. 使用範例
現在你可以在任何元件中使用 Tailwind 的類名:
export default function Hero() {
return (
<div className="bg-blue-500 p-8 rounded-lg shadow-xl">
<h1 className="text-white text-3xl font-bold">歡迎來到 Next.js</h1>
<p className="text-blue-100 mt-2">這是一個使用 Tailwind 設計的區塊。</p>
</div>
);
}
CSS Modules
如果你偏好將 CSS 邏輯與 HTML 分離,CSS Modules 是最佳選擇。它會自動為類名加上獨一無二的雜湊值 (Hash),避免全域樣式衝突。
使用步驟
- 建立
.module.css結尾的檔案。 - 在元件中匯入並使用。
/* app/dashboard/styles.module.css */
.card {
padding: 20px;
border-radius: 8px;
background: #f9f9f9;
}
.title {
color: #333;
}
// app/dashboard/page.tsx
import styles from './styles.module.css';
export default function Dashboard() {
return (
<div className={styles.card}>
<h2 className={styles.title}>儀表板概覽</h2>
</div>
);
}
全域樣式 (Global CSS)
全域樣式通常用於設定 CSS Reset、定義主題色變數或全站字體。
- 規則:除了
app/layout.tsx外,你不能在任何 Server Component 中直接匯入非 Module 的 CSS 檔案。
/* app/globals.css */
:root {
--primary-color: #0070f3;
}
body {
font-family: 'Inter', sans-serif;
color: var(--primary-color);
}
並在 app/layout.tsx 中匯入該檔案:
import './globals.css';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
);
}
進階:Sass 支援
Next.js 內建支援 Sass。你只需要安裝套件:
npm install --save-dev sass
安裝後,你可以將檔案副檔名改為 .scss 或 .sass(包含 Module 的形式如 Button.module.scss),Next.js 會自動為你處理編譯。
應該如何選擇?
- 中大型專案:強烈建議使用 Tailwind CSS。它能保持樣式的一致性,且不會隨著專案變大而讓 CSS 檔案無限膨脹。
- 小型元件庫或個人偏好:使用 CSS Modules。如果你習慣寫傳統 CSS,這是最安全且支援性最好的方式。
在 Next.js 中開發時,建議搭配 VS Code 的 Tailwind CSS IntelliSense 擴充功能,它能提供語法自動補全與預覽,讓開發體驗提升一個層級。