Styling in NextJS
Next.js allows several possibilities for styling:
- Built-in support for CSS and Sass which allows you to import
.css
and.scss
files (still needsnpm install sass
) - Built-in support for CSS modules via
import ./mycomponent.module.css
which will automatically generate unique class names. Next.js’s code splitting feature works on CSS Modules as well. It ensures the minimal amount of CSS is loaded for each page. - CSS-in-JS libraries such as styled-jsx (built-in support), styled-components or emotion
- Using popular CSS libraries like Tailwind CSS
To load global CSS files, create a file called pages/_app.js
and import styles/global.css
for example:
// pages/_app.js import '../styles/global.css' // also direct imports from node_modules are allowed import 'bootstrap/dist/css/bootstrap.css' export default function App({ Component, pageProps }) { return <Component {...pageProps} /> }
This App
component is the top-level component which will be common across all the different pages. You can use this App
component to keep state when navigating between pages, for example. You cannot import global CSS anywhere else.
Customizing PostCSS Config
Out of the box, with no configuration, Next.js compiles CSS using PostCSS. To customize PostCSS config, you can create a top-level file called postcss.config.js
. This is useful if you’re using libraries like Tailwind CSS.
npm install tailwindcss postcss-preset-env postcss-flexbugs-fixes
// postcss.config.js module.exports = { plugins: [ 'tailwindcss', 'postcss-flexbugs-fixes', [ 'postcss-preset-env', { autoprefixer: { flexbox: 'no-2009' }, stage: 3, features: { 'custom-properties': false } } ] ] }
// tailwind.config.js module.exports = { purge: [ // Use *.tsx if using TypeScript './pages/**/*.js', './components/**/*.js' ] // ... }