Next.js CSS Styles | Rookie Tutorial
In Next.js, the use of styles is very flexible, and we can choose multiple ways to add styles to your application.
* * *
## Global Styles
Global styles are CSS styles that affect the entire application, typically used to set the basic styles of a page, such as fonts, colors, layout, etc.
Next.js imports global CSS files through app/layout.tsx.
By default, the app directory already has a global styles file named globals.css. If it doesn't exist, you can also create a new CSS file.
Create a globals.css file in the styles directory, and then import it in app/layout.tsx.
## app/globals.css File Code:
/* app/globals.css */
body {
padding:20px 20px 60px;
max-width:680px;
font-size:64px;
margin:0 auto;
background-color:#F5F5FB;
color:#333;
}
Then, import this file in the root layout (app/layout.tsx) to apply the styles to every route in the application:
## app/layout.tsx File Code:
// app/layout.tsx
// These styles will apply to every route in the application
import'./globals.css'
export default function RootLayout({
children,
}:{
children: React.ReactNode
}){
return(
{children}
)
}
**Note:** Global styles can be imported into any layout, page, or component in the app directory. However, since Next.js uses React's built-in stylesheet support for integration with Suspense, the current built-in support does not remove stylesheets when you navigate between routes. Therefore, we recommend using global styles for truly global CSS, and CSS Modules for scoped CSS.
app/page.tsx code is as follows:
## Example
export default function Home(){
return
Hello, !
;
}
Visit http://localhost:3000/ to test the display effect as shown below:
!(#)
* * *
## Sass
Next.js also supports Sass, a more feature-rich CSS preprocessor.
If you prefer to use Sass for writing styles, you can enable it by installing the corresponding dependencies. For content, please refer to the (#).
Installation:
npm install sass
Next.js integrates with Sass, supporting .scss and .sass extensions and syntax.
You can also use component-level Sass through CSS Modules, with extensions .module.scss or .module.sass.
### Custom Sass Configuration
If you want to configure Sass options, you can use the sassOptions option in next.config.js.
## Example
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig ={
sassOptions:{
additionalData: `$var: red;`,// Automatically inject these styles into every Sass file
},
}
export default nextConfig
In this way, you can configure some default Sass data or perform other custom settings.
Create an SCSS file, such as styles/Button.module.scss:
## Example
/* styles/Button.module.scss */
.button{
padding:10px 20px;
background-color:#0070f3;
color:white;
border:none;
border-radius:5px;
cursor:pointer;
}
Use the SCSS module in a component:
## Example
// app/components/Button.tsx
import styles from '../styles/Button.module.scss';
export default function Button(){
return;
}