CSS Modules
CSS Modules scope CSS locally by automatically generating unique class names. Create a file with the.module.css extension:
components/Button.module.css
components/Button.tsx
Button_button__abc12), so there are no naming conflicts between components.
Global CSS
Import global CSS files inpages/_app.tsx. They apply to every page in your application.
styles/globals.css
pages/_app.tsx
styled-jsx
styled-jsx is built into Next.js. It provides scoped CSS within a component using a<style jsx> tag:
pages/index.tsx
Global styles with styled-jsx
Add theglobal attribute to apply styles globally from within a component:
The App Router does not include styled-jsx by default. CSS Modules and Tailwind CSS are the recommended styling options for new projects.
Sass
Next.js has built-in support for Sass (.scss and .sass files). Install the sass package first:
.module.scss for scoped styles or import .scss files globally in _app.tsx:
Configuring Sass options
You can pass options to the Sass compiler innext.config.js:
next.config.js
CSS-in-JS
CSS-in-JS libraries that require server-side rendering (such as styled-components or Emotion) need additional setup for the Pages Router. They require customizingpages/_document.tsx to inject styles on the server.
styled-components
Install styled-components:.babelrc to enable the plugin:
.babelrc
_document.tsx to collect and inject styles during SSR:
pages/_document.tsx
components/Button.tsx
Emotion
Emotion requires a similar_document.tsx customization. Refer to the Emotion SSR documentation for the exact setup.
Tailwind CSS
To use Tailwind CSS in a Pages Router project, install it and configure PostCSS:tailwind.config.js to include your files:
tailwind.config.js
_app.tsx:
styles/globals.css
