tips / nextjs
How to style using emotion with Global Styles in Next.js
September 11, 2022
What is Emotion?
Emotion is a library designed for wrting css styles with JavaScript.
Step 1: Install Emotion
npm install --save @emotion/react
Step 2: Create global style
const global = css`
body {
color: #333;
}
`
Step 3: Import Global and css in _app.tsx
import { Global, css } from '@emotion/react'
Step 4: Add Global component and styles
<Global styles={global} />
This is _app.tsx file.
// _app.tsx
import type { AppProps } from 'next/app'
import { Global, css } from '@emotion/react'
export default function MyApp({ Component, pageProps }: AppProps) {
const global = css`
body {
color: #333;
}
`
return (
<>
<Global styles={global} />
<Component {...pageProps} />
</>
)
}
Optional 1: Make global style file (global-style.ts)
Create global-style.ts file.
// global-style.ts
import { css } from '@emotion/react'
export const global = css`
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
body {
color: white;
background: black;
}
}
`
Import global-style.ts file in _app.tsx
// _app.tsx
import type { AppProps } from 'next/app'
import { Global } from '@emotion/react'
import { global } from '@styles/globals-style'
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<Global styles={global} />
<Component {...pageProps} />
</>
)
}
Optional 2: Using normalize.css
Install normalize.css.
npm install --save normalize.css
Import normalize.css file in global-style.css
// global-style.ts
import 'normalize.css'
import { css } from '@emotion/react'
export const global = css`
...
`
References
- Emotion – Global Styles https://emotion.sh/docs/globals(2022-9-11参照)