CSS in next-js

  • global stylesheet
  • component-level CSS
    • CSS modules
    • styled-jsx
  • inline css

Inline CSS

The simplest way to add style is inline styles

example

<p>first paragraph</p>
<p style={{ color: 'red' }}>second paragraph</p>

if the style depends on the data coming from an api request, then inline style is the best choice

<div style={{
      backgroundImage: `url("${imageUrl}")`,
    }} />

CSS modules

A CSS Module is a CSS file in which all class names are scoped locally by default.
This allows you to use the same CSS class name in different files without worrying about collisions.
Next.js supports CSS Modules using the [name].module.css file naming convention.

example

file components/Button.module.css

.btn {
    color: white;
    border-radius: 4px;
    font-size: large;
}

.primary {
    composes: btn;
    background-color: green;
}

.danger {
    composes: btn;
    background-color: red;
}

file components/Button.js

import styles from './Button.module.css';

export default () => (
    <button
      type="button"
      className={styles.primary}
    >
      click here
    </button>
);

styled-jsx

styled-jsx is another way to add a component-level CSS.
you can skip scoping entirely by adding global.

example

export default () => (
    <>
        <h2>title</h2>
        <p>paragraph</p>
        
        <style jsx>{`
            h2 {
              font-family: Arial;
            }
            p {
              color: blue;
            }
        `}</style>
        
        <style global jsx>{`
            body {
              background: gray;
            }
      `}</style>
    </>
);

Custom App page

allows you to do things like:

  • Add global CSS
  • Persisting layout between page changes
  • Keeping state when navigating pages
  • Inject additional data into pages

example

pages/_app.js

import Navbar from "../components/navbar";
import '../css/style.css';

const App = ({ Component, pageProps }) => (
  <>
    <Navbar />
    <Component {...pageProps} />
  </>
);

export default App;

importing css files is only allowed inside pages/_app.js to prevent collisions


Resources

Select a repo