Styles are an important part of web applications. CSS is a language we can add to any application.
NextJS supports CSS styles in different ways
- Global Styles
- Third-party Styles
- Component scope Styles
- CSS-in-JS
- Sass/scss
- Normal CSS link attribute.
In Production, all CSS files are appended and crated single minified CSS file except component-scoped styled
In Development, you can modify and test CSS as it supports hot reloading all styles.
NextJS CSS Global CSS styles
Global styles are applied to all the components and pages in the Application.
Layout and template changes are placed in global styles.
For example, Consider creating a styles.css
file in the application/styles
folder.
styles.css
body{
color:blue;
}
a{
cursor: pointer;
font-size: 24px;
text-decoration: underline;
}
Let’s import this styles.css in pages/_app.js
. This file is created by default in the pages folder with the create-next-app CLI tool.
if this file does not exist, create a file in the pages folder
pages/_app.js:
import '../styles/styles.css'
import type { AppProps } from 'next/app'
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
export default MyApp
Global styles apply to the entire application. It is always best to use layout and template CSS changes. Any specific component styles are applied in the Component scope.
How to add Component styles to NextJS using CSS modules.
In this, Each react component or page is added with component scoped styles.
NextJS supports component scope with CSS modules.
These are applied with [component].module.css
files. where the component is the name of the page file.
For example, Consider you have the about.tsx
file in the pages folder, Then you have the about.module.css
file in the pages
folder.
This is an optional feature, you can add a component with .module.css
file name syntax.
about.module.css:
.heading{
font-size: 25;
font-weight: 700;
}
In react component,
Import styled CSS file using the import
keyword.
apply styles using react CSS className with javascript expression syntax{}
about.tsx:
import styles from './about.module.css'
export default function AboutPage() {
return <div className={styles.heading}>About Page</div>
}
In production, component scoped CSS is appended and minified and code is split into multiple files.