Skip to content

Next.js - CSS 支持

Next.js 提供了几种样式化应用的方式,以满足不同的偏好和项目需求。现代 Web 开发通常涉及组件范围内的样式(component-scoped styles),以避免冲突并提高可维护性。

最常见且推荐的方法之一是使用 CSS Modules。这种技术会自动将 CSS 类名局部限定在组件范围内(scope),防止全局命名空间冲突。

在本例中,我们将使用 CSS Modules 创建一个简单的 Layout 组件,提供基本的结构和样式。

假设你有一个标准的 Next.js 项目设置(例如,使用 create-next-app 创建的项目)。

首先,如果根目录下没有 components 目录,请创建一个。在 components 目录内,创建一个名为 layout.module.css 的文件,内容如下:

.container {
max-width: 36rem;
padding: 0 1rem;
margin: 3rem auto 6rem;
border: 1px solid #eaeaec;
border-radius: 8px;
}

注意像 max-width 和 border-radius 这样的 CSS 属性是如何书写的。CSS Modules 文件通常以 .module.css 结尾。

接下来,在 components 目录中创建对应的组件文件 layout.js(或 layout.jsx):

import styles from './layout.module.css';
function Layout({ children }) {
return <div className={styles.container}>{children}</div>;
}
export default Layout;

在这里,我们将 CSS 模块导入为 styles。Next.js 为 .container 生成的唯一类名(例如 layout_container__XYZ12)可以通过 styles.container 访问。这确保了样式仅应用于此组件内部。

现在,让我们在其中一个页面中使用这个 Layout 组件,例如 pages/posts/first-post.js:

import Link from 'next/link';
import Head from 'next/head';
import Layout from '../../components/layout';
export default function FirstPost() {
return (
<Layout>
<Head>
<title>My First Post</title>
</Head>
<h1>My First Post</h1>
<h2>
<Link href="/">
<a>Back to home</a>
</Link>
</h2>
<p>This is the content of the first post, wrapped by our Layout component.</p>
</Layout>
);
}

Next.js 中其他常用的样式化方法包括:

  • 全局 CSS: 适用于基础样式(详见下一章)。
  • Tailwind CSS: 一个实用至上的 CSS 框架,与 Next.js 集成良好。
  • CSS-in-JS 库: 例如 styled-components 或 Emotion,允许直接在 JavaScript/TypeScript 文件中编写 CSS。
  • Sass/SCSS: Next.js 内置支持 Sass。

选择哪种方法取决于你的项目规模、团队偏好和具体需求。对于许多项目来说,CSS Modules 在功能和简洁性之间提供了很好的平衡。

确保你的 Next.js 开发服务器正在运行:

npm run dev
# Example Output:
# ready - started server on 0.0.0.0:3000, url: http://localhost:3000
# event - compiled client and server successfully in 184 ms (20 modules)
# wait - compiling /posts/first-post (client and server)...
# event - compiled client and server successfully in 212 ms (47 modules)

在浏览器中访问 /posts/first-post(例如 http://localhost:3000/posts/first-post)。你应该看到 ‘My First Post’ 页面的内容居中显示在一个容器内,该容器具有浅灰色边框和一些内边距/外边距,这正是 layout.module.css 中定义的样式。