Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying global styles in Next.js

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>
    );
  }
}
like image 796
EverydayDeveloper Avatar asked Aug 31 '26 05:08

EverydayDeveloper


1 Answers

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

like image 125
ddon-90 Avatar answered Sep 02 '26 21:09

ddon-90



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!