Applying global styles in Next.js

EverydayDeveloper picture EverydayDeveloper · Mar 9, 2020 · Viewed 6.9k times · Source

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>
    );
  }
}

Answer

ddon-90 picture ddon-90 · Mar 9, 2020

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