Skip to content

Styling Next.js components using CSS

New Course Coming Soon:

Get Really Good at Git

How to style React components in Next.js?

How do we style React components in Next.js?

We have a lot of freedom, because we can use whatever library we prefer.

But Next.js comes with styled-jsx built-in, because that’s a library built by the same people working on Next.js.

And it’s a pretty cool library that provides us scoped CSS, which is great for maintainability because the CSS is only affecting 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>

If you want to import an external CSS file in a Next.js component, you have to first install @zeit/next-css:

npm install @zeit/next-css

and then create a configuration file in the root of the project, called next.config.js, with this content:

const withCSS = require('@zeit/next-css')
module.exports = withCSS()

After restarting the Next app, you can now import CSS like you normally do with JavaScript libraries or components:

import '../style.css'

You can also import a SASS file directly, using the @zeit/next-sass library instead.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!

Here is how can I help you: