Next.js(TypeScript)全局样式设置:消除body默认8px边距遇阻
Let's break down why your attempts weren't working and fix this step by step:
1. The Problem with Your Current <style jsx global> Approach
Your existing code targets a div with the .body class instead of the actual <body> element. The :global() syntax here is misplaced, and you don't need to wrap a class to target the global body.
Corrected <style jsx global> Implementation
If you want to stick with styled-jsx, update your code (better yet, put this in _app.tsx for app-wide coverage) to directly target the <body> tag:
class Index extends React.Component { render() { return ( <Container> <style jsx global>{` /* Target the actual body element directly */ body { margin: 0; padding: 0; /* Optional but often useful to reset default padding */ } /* Optional: Standardize box-sizing for easier layout across elements */ * { box-sizing: border-box; } `}</style> <NavBar /> </Container> ); } }
2. Recommended: Use Emotion's Global Component (Since You're Already Using Emotion)
Emotion provides a dedicated Global component for global styles, which is the most reliable method when working with Emotion in Next.js.
Update your _app.tsx like this:
// _app.tsx import { Global, css } from '@emotion/react'; import type { AppProps } from 'next/app'; function MyApp({ Component, pageProps }: AppProps) { return ( <> {/* Global styles applied to all pages */} <Global styles={css` body { margin: 0; padding: 0; box-sizing: border-box; } html { margin: 0; padding: 0; } `} /> <Component {...pageProps} /> </> ); } export default MyApp;
This ensures the global body styles load once for all pages, eliminating any scope or loading order issues.
3. Alternative: Use a Global CSS File (Next.js Native Approach)
If you prefer plain CSS, create a global styles file (e.g., styles/globals.css) and import it only in _app.tsx (Next.js enforces this for global CSS to avoid conflicts):
/* styles/globals.css */ html, body { margin: 0; padding: 0; box-sizing: border-box; }
Then import it in _app.tsx:
// _app.tsx import '../styles/globals.css'; import type { AppProps } from 'next/app'; function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} />; } export default MyApp;
Key Takeaways
- Your initial code wasn't targeting the actual
<body>element—you were styling a div with a.bodyclass instead. - For Emotion users, the
Globalcomponent is the cleanest way to apply global styles across your Next.js app. - Always place global styles (whether styled-jsx, Emotion Global, or plain CSS) in
_app.tsxto ensure they apply to all pages.
内容的提问来源于stack exchange,提问作者EverydayDeveloper

