Applying global styles in Next.js

13,959

Solution 1

You need some global styles (<style jsx global>) to style the body element or provide css resets.

Example:

import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: red;
      }
    `}</style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);

Code Sandbox

Solution 2

You can have global styles using emotion with Next.js

In your _app.tsx file, you must to

import { Global, css } from '@emotion/core'

return (
  <>   
    <Global styles={css` /* styles */ `}/>
    <Component {...pageProps} />
  </>

You can see how to implement it, here

https://github.com/pabloobandodev/social-media/blob/master/pages/_app.tsx

enter image description here

Share:
13,959
EverydayDeveloper
Author by

EverydayDeveloper

Updated on July 02, 2022

Comments

  • EverydayDeveloper
    EverydayDeveloper almost 2 years

    I am using Next.js with Typescript. The margin of the body is default 8px and I want to get it to 0px. When I try to add an external style sheet to my index.tsx file it throws an error that you can only add external stylesheet to _app.tsx. However, even when I try to import in my _app.tsx, it doesn't change the global style of the body. I am using Emotion css for the styling part. Is there a different way to change the style of the body in the index file using global style? Here is my index.tsx code and I have tried adding the global styles using Emotion CSS as well but it doesn't work.

    class Index extends React.Component {
      render() {
        return (
          <div className='body'>
            <Container>
              <style jsx global>{`
                .body:global() {
                  margin: 0px;
                }
              `}</style>
              <NavBar />
            </Container>
          </div>
        );
      }
    }
    
  • EverydayDeveloper
    EverydayDeveloper about 4 years
    It doesn't help. I have updated my code, still Next does not accept the margin of the body @ddon-90
  • ddon-90
    ddon-90 about 4 years
    You have .body which mean class"body" as CSS class. Remove the dot that precedes body if you want to target the HTML tag <body>. Also global() is not needed. I've added a code sandbox as an example.
  • yoyo
    yoyo about 3 years
    Could you explain what is this <style jsx global />? I mean, is it a feature from Next or react?