Applying global styles in Next.js
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>
);
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
EverydayDeveloper
Updated on July 02, 2022Comments
-
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 myindex.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 about 4 yearsIt doesn't help. I have updated my code, still Next does not accept the margin of the body @ddon-90
-
ddon-90 about 4 yearsYou have
.body
which meanclass"body"
as CSS class. Remove the dot that precedesbody
if you want to target the HTML tag<body>
. Alsoglobal()
is not needed. I've added a code sandbox as an example. -
yoyo about 3 yearsCould you explain what is this
<style jsx global />
? I mean, is it a feature from Next or react?