CSS Styling in NextJS
Next.js has built-in support for CSS and Sass, which allows you to import .css
and .scss
files.
Next.js has a built-in library called styled-jsx. It’s a “CSS-in-JS” library — it lets you write CSS within a React component, and the CSS styles will be scoped (other components won’t be affected).
You can also use other popular CSS-in-JS libraries such as styled-components or emotion.
Component Level Styles
Defining CSS Module
To use CSS Modules in NextJS, the CSS file name must end with .module.css.
Eg. A CSS Module is present in components/layout.module.css
with the following content
.container { max-width: 36rem; padding: 0 1rem; margin: 3rem auto 6rem; }
Using CSS Module
To use this container class inside components/layout.js, you need to:
- Import the CSS file and assign a name to it, like styles
- Use styles.container as the className
import styles from "./layout.module.css"; export default function Layout({ children }) { return <div className={styles.container}>{children}</div>; }
Autogenerated Unique Classnames
If you look at the HTML in your browser’s devtools, you’ll notice that the div rendered by the Layout component has a unique class name as shown below
CSS Modules automatically generates unique class names, preventing class name collisions.
Inaddition, Next.js’s code splitting feature works on CSS Modules as well. It ensures the minimal amount of CSS is loaded for each page. This results in smaller bundle sizes.
CSS Modules are extracted from the JavaScript bundles at build time and generate .css files that are loaded automatically by Next.js.
Global Styles
In Next.js, We can add global CSS files by importing them from pages/_app.js
. We cannot import global CSS anywhere else.
If pages/_app.js
doesn't exist in our project, create a file called pages/_app.js with the following content:
export default function App({ Component, pageProps }) { return <Component {...pageProps} />; }
App component is the top-level component which will be common across all the different pages.
We can also use app component to keep state when navigating between pages.
We need to restart the development server when you add pages/_app.js
. Press Ctrl + c
to stop the server and run npm run dev
You can place the global CSS file anywhere and use any name.
A good practice is to create a top-level styles
directory and create global.css
inside it.
Finally, open pages/_app.js
add import the CSS file as shown below
import '../styles/global.css'