Global CSS
Global CSS in Next.js lets you define styles that apply across your entire application. This is useful for base styles, typography, and CSS resets that should be consistent everywhere.
Think of global CSS as the foundation of your house. It provides the base upon which all other styles are built.
Adding Global Styles
In Next.js, you can add global styles by importing a CSS file in your root layout:
// app/layout.js
import './globals.css';
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
The globals.css file is imported at the top level, making its styles available throughout your application.
Common Global Styles
Here's what a typical global CSS file might contain:
/* app/globals.css */
/* CSS Reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Base Typography */
html {
font-size: 16px;
scroll-behavior: smooth;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6;
color: #333;
}
/* Global Link Styles */
a {
color: #0070f3;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* Global Button Styles */
button {
font-family: inherit;
}
These styles create a consistent base for your application.
CSS Variables
Global CSS is a great place to define CSS variables for your design system:
:root {
--primary-color: #0070f3;
--secondary-color: #ff0080;
--background: #ffffff;
--text-color: #333333;
--border-radius: 8px;
--shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
body {
background-color: var(--background);
color: var(--text-color);
}
These variables can be used in both global and component-specific styles, ensuring consistency.
Global vs Scoped Styles
Understanding when to use global vs scoped styles is important:
Use global styles for:
- CSS resets and base styles
- Typography and font settings
- CSS variables and design tokens
- Utility classes that are used everywhere
Use scoped styles (CSS Modules) for:
- Component-specific styles
- Styles that should be isolated
- Complex layouts that might conflict
A good rule of thumb: keep global styles minimal and use CSS Modules for everything else.