Next.js【详解】CSS 样式方案

全局样式 Global CSS

  1. 默认已创建,即 src\app\globals.css,可根据需要修改

  2. 默认在全局布局中导入
    src\app\layout.tsx

    import "./globals.css";
    

组件样式 CSS Modules

  1. 新建文件 src\app\test\styles.module.css

    .red {
          
          
        color: red;
      }
    
  2. 导入目标页面使用
    src\app\test\page.tsx

    import styles from "./styles.module.css";
    
    export default function Page() {
          
          
      return <main className={
          
          styles.red}>主体内容</main>;
    }
    

最终效果如下:

在这里插入图片描述
字体的实现见 https://blog.csdn.net/weixin_41192489/article/details/145625560

CSS 框架 Tailwind CSS

创建项目时,选择采用 Tailwind CSS 即可自动集成使用

Tailwind CSS 官网为 https://tailwindcss.com/docs/installation/using-vite

Tailwind CSS 实用教程见 https://blog.csdn.net/2401_83384536/article/details/140352836

使用范例

<h1 className="text-3xl font-bold underline">Hello, Next.js!</h1>

CSS 预处理 Sass

  1. 安装 sass

    扫描二维码关注公众号,回复: 17585714 查看本文章
    pnpm i --save-dev sass
    
  2. 在目标页面文件同目录下创建 scss 文件,如 src\app\test\test.module.scss

    .container {
          
          
      background-color: yellow;
    
      h1 {
          
          
        color: red;
      }
    }
    
  3. 页面中导入使用
    src\app\test\page.tsx

    import styles from "./test.module.scss";
    
    export default function Home() {
          
          
      return (
        <div className={
          
          styles.container}>
          <h1>在 Next.js 中使用 Sass!</h1>
        </div>
      );
    }
    

效果如下

在这里插入图片描述

组件中编写样式 styled-jsx

Next.js 内置支持 styled-jsx , 但仅适用于客户端组件

// 客户端组件
"use client";
export default function Page() {
    
    
  return (
    <>
      <div>
        <h1>在 Next.js 中使用 Sass!</h1>
      </div>
      <style jsx>{
    
    `
        h1 {
          color: red;
        }
      `}</style>
    </>
  );
}