Assets, Metadata, and CSS

Styling Tips

Here are some styling tips that might be helpful.

You can just read through the following sections. No need to make changes to our app!

Using classnames library to toggle classes

classnames is a simple library that lets you toggle class names easily. You can install it using npm install classnames or yarn add classnames.

Please take a look at its documentation for more details, but here’s the basic usage:

  • Suppose that you want to create an Alert component which accepts type, which can be 'success' or 'error'.
  • If it’s 'success', you want the text color to be green. If it’s 'error', you want the text color to be red.

You can first write a CSS module (e.g. alert.module.css) like this:

.success {
  color: green;
}
.error {
  color: red;
}

And use classnames like this:

import styles from './alert.module.css'
import cn from 'classnames'

export default function Alert({ children, type }) {
  return (
    <div
      className={cn({
        [styles.success]: type === 'success',
        [styles.error]: type === 'error'
      })}
    >
      {children}
    </div>
  )
}

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.

Here are the steps to add Tailwind CSS. We recommend using postcss-preset-env and postcss-flexbugs-fixes to match Next.js’s default behavior. First, install the packages:

npm install tailwindcss postcss-preset-env postcss-flexbugs-fixes

Then write the following for postcss.config.js:

module.exports = {
  plugins: [
    'tailwindcss',
    'postcss-flexbugs-fixes',
    [
      'postcss-preset-env',
      {
        autoprefixer: {
          flexbox: 'no-2009'
        },
        stage: 3,
        features: {
          'custom-properties': false
        }
      }
    ]
  ]
}

We also recommend removing unused CSS by specifying the purge option on tailwind.config.js:

// tailwind.config.js
module.exports = {
  purge: [
    // Use *.tsx if using TypeScript
    './pages/**/*.js',
    './components/**/*.js'
  ]
  // ...
}

To learn more about custom PostCSS configuration, check out the documentation for PostCSS.

Using Sass

Out of the box, Next.js allows you to import Sass using both the .scss and .sass extensions. You can use component-level Sass via CSS Modules and the .module.scss or .module.sass extension.

Before you can use Next.js' built-in Sass support, be sure to install sass:

npm install sass

That’s it for this lesson!

To learn more about Next.js’s built-in CSS Support and CSS Modules, check out the CSS Documentation.