emotion の Global
コンポーネントを使用するとサイト全体に共通のcssを適用することができます。
@emotion/react
はインストール済みとします。
導入方法
全体に適用する css を用意する
const global = css`
body {
color: #333;
}
`;
_app.tsx で Global コンポーネントを import する
import { Global, css } from "@emotion/react";
Global コンポーネントにスタイルを適用する
<Global styles={global} />
_app.tsx の全体
// _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} />
</>
)
}
グローバル css を別ファイルにする場合
global.ts を作成してスタイルを記述する
※ css は Next.js のデフォルトのスタイルです。
// global.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;
}
}
`;
_app.tsx で読み込み、Global コンポーネントに適用する
// _app.tsx
import type { AppProps } from 'next/app'
import { Global } from '@emotion/react'
import { global } from '@styles/globals'
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<Global styles={global} />
<Component {...pageProps} />
</>
)
}
normalize.css を併用する場合
**normalize.css をインストールする**
npm install --save normalize.css
global.ts で読み込む
// global.ts
import "normalize.css";
参照
- Emotion – Global Styles https://emotion.sh/docs/globals(2022-9-11参照)