Styling Next.js components using CSS
By Flavio Copes
Learn how to style Next.js components with built-in CSS and Sass support, CSS Modules, and styled-jsx scoped styles, without the old Zeit CSS plugins.
How do we style React components in Next.js?
We have a lot of freedom, because we can use whatever library we prefer.
On Next.js 16, CSS and Sass are built in. You do not need a special plugin for that.
You can also use styled-jsx, which still ships with Next.js. It gives you scoped CSS, which is great for maintainability because the CSS only affects the component it’s applied to.
I think this is a great approach at writing CSS, without the need to apply additional libraries or preprocessors that add complexity.
To add CSS to a React component in Next.js we insert it inside a snippet in the JSX, which start with
<style jsx>{`
and ends with
`}</style>
Inside this weird blocks we write plain CSS, as we’d do in a .css file:
<style jsx>{`
h1 {
font-size: 3rem;
}
`}</style>
You write it inside the JSX, like this:
const Index = () => (
<div>
<h1>Home page</h1>
<style jsx>{`
h1 {
font-size: 3rem;
}
`}</style>
</div>
)
export default Index
Inside the block we can use interpolation to dynamically change the values. For example here we assume a size prop is being passed by the parent component, and we use it in the styled-jsx block:
const Index = props => (
<div>
<h1>Home page</h1>
<style jsx>{`
h1 {
font-size: ${props.size}rem;
}
`}</style>
</div>
)
If you want to apply some CSS globally, not scoped to a component, you add the global keyword to the style tag:
<style jsx global>{`
body {
margin: 0;
}
`}</style>
For a global stylesheet file, import it from the root layout (App Router) or from pages/_app.js (Pages Router):
import '../styles/globals.css'
CSS Modules work out of the box too. Name a file Button.module.css, import it, and use the class names as an object:
import styles from './Button.module.css'
export default function Button() {
return <button className={styles.primary}>Save</button>
}
For Sass, install the sass package and import a .scss or .sass file the same way. Old packages like @zeit/next-css and @zeit/next-sass are obsolete. You do not need them on modern Next.js.
If you prefer a CSS-in-JS library instead, Styled Components is still a common option beside the built-in tools.
Want me to talk about your product? You can sponsor this site.
Related posts about next: