Next.js Global CSS
In web development, styling your application is just as important as its functionality. Next.js offers several ways to style your applications, and one of the most fundamental approaches is using global CSS. This tutorial will guide you through implementing global CSS in your Next.js projects.
What is Global CSS?
Global CSS refers to stylesheets that apply across your entire application. Once defined, these styles affect every page and component within your Next.js project. This is particularly useful for:
- Setting up consistent typography
- Defining color schemes
- Applying reset CSS rules
- Creating base styles for common HTML elements
- Implementing site-wide design systems
How Global CSS Works in Next.js
Unlike component-level styling that's scoped to specific elements, global CSS applies throughout your application. Next.js has specific conventions for including and managing global styles.
Adding Global CSS to Your Next.js Application
Step 1: Create a Global CSS File
First, create a CSS file that will contain your global styles. The convention is to place this in a styles
directory in your project root:
mkdir -p styles
touch styles/globals.css
Step 2: Add Some Global Styles
Let's add some basic global styles to styles/globals.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: #0070f3;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
* {
box-sizing: border-box;
}
These styles set default margins and padding for the page, define a font family, style links, and ensure all elements use the border-box box sizing model.
Step 3: Import the Global CSS in _app.js
To apply global CSS, you must import it in the special _app.js
file. If you don't have this file yet, create it in the pages
directory:
// pages/_app.js
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
In Next.js, global CSS can only be imported in the _app.js
file. Attempting to import global CSS in any other file will result in errors.
The _app.js
File Explained
The _app.js
file in Next.js is a special component that:
- Initializes pages
- Keeps state when navigating between pages
- Adds global styles
- Can include layouts shared across all pages
When a user visits your Next.js application, the _app.js
component initializes first, wrapping all other page components.
Example: Creating a Theme with Global CSS
Let's explore a practical example of using global CSS to create a consistent theme across your application:
/* styles/globals.css */
:root {
--primary-color: #0070f3;
--secondary-color: #ff6b81;
--background-color: #ffffff;
--text-color: #333333;
--heading-font: 'Poppins', sans-serif;
--body-font: 'Open Sans', sans-serif;
}
body {
background-color: var(--background-color);
color: var(--text-color);
font-family: var(--body-font);
line-height: 1.6;
}
h1, h2, h3, h4, h5, h6 {
font-family: var(--heading-font);
margin-top: 1.5rem;
margin-bottom: 1rem;
}
a {
color: var(--primary-color);
transition: color 0.3s ease;
}
a:hover {
color: var(--secondary-color);
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 1rem;
}
.btn {
display: inline-block;
background: var(--primary-color);
color: white;
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
font-family: var(--body-font);
}
.btn:hover {
background: var(--secondary-color);
}
This CSS defines CSS variables (custom properties) for colors and fonts, then uses those variables throughout the stylesheet for consistency. This approach makes it easy to update your theme by changing the variable values in one place.
Working with CSS Reset/Normalize
Many developers start their projects with a CSS reset or normalize to ensure consistent styling across different browsers.
Adding Normalize.css
You can add a CSS reset like Normalize.css to your global styles:
- First, install Normalize.css:
npm install normalize.css
- Then import it in your
_app.js
file before your global CSS:
// pages/_app.js
import 'normalize.css';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
Using Global CSS with CSS Modules
You can use global CSS alongside CSS Modules in Next.js. While global CSS applies to your entire application, CSS Modules allow for component-specific styling without conflicts.
For example:
// pages/about.js
import styles from '../styles/About.module.css';
export default function About() {
// The .container class from globals.css applies
// The .title class from About.module.css only applies to this component
return (
<div className="container">
<h1 className={styles.title}>About Us</h1>
<p>Our company has been in business for over 10 years.</p>
</div>
);
}
Best Practices for Global CSS in Next.js
-
Keep global styles minimal: Only include truly global styles in your globals.css file. Component-specific styles should use CSS Modules or other scoped styling solutions.
-
Use CSS variables for theming: Define color schemes, typography, and spacing as CSS variables in your global CSS for easy theme management.
-
Organize your global CSS: Consider breaking your global CSS into logical sections like reset, typography, colors, and utility classes.
-
Consider media queries: Include responsive breakpoints in your global CSS for consistent responsive behavior.
-
Don't over-rely on global classes: While convenient, too many global utility classes can lead to bloated HTML and maintenance challenges.
Example: Dark Mode with Global CSS Variables
Here's a practical example of implementing a simple dark/light theme toggle using global CSS variables:
/* styles/globals.css */
:root {
/* Light theme (default) */
--bg-color: #ffffff;
--text-color: #333333;
--card-bg: #f0f0f0;
}
[data-theme="dark"] {
/* Dark theme */
--bg-color: #121212;
--text-color: #e0e0e0;
--card-bg: #1e1e1e;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s ease, color 0.3s ease;
}
.card {
background-color: var(--card-bg);
padding: 1rem;
border-radius: 8px;
}
And the corresponding JavaScript to toggle the theme:
// components/ThemeToggle.js
export default function ThemeToggle() {
const toggleTheme = () => {
// Check if document is available (client-side only)
if (typeof document !== 'undefined') {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
// Optionally save to localStorage for persistence
localStorage.setItem('theme', newTheme);
}
};
return (
<button onClick={toggleTheme} className="theme-toggle-btn">
Toggle Theme
</button>
);
}
To initialize the theme based on user preference, you'd add this in a useEffect or similar client-side code:
// In a layout component or _app.js
useEffect(() => {
// Check for saved theme preference or use system preference
const savedTheme = localStorage.getItem('theme') ||
(window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', savedTheme);
}, []);
Summary
Global CSS in Next.js provides a powerful way to establish consistent styling across your entire application. Remember these key points:
- Global CSS must be imported in
_app.js
- Use global CSS for site-wide styles, resets, and variables
- Combine global CSS with CSS Modules for a flexible styling strategy
- Use CSS variables to create themeable applications
- Follow best practices to keep your styles maintainable
By mastering global CSS in Next.js, you'll be able to create cohesive, maintainable styling systems that provide a consistent user experience across your entire application.
Additional Resources
Exercise
Try creating a Next.js application with:
- A global CSS file with variables for a color scheme
- A layout component that uses your global styles
- A theme toggle button that switches between light and dark modes
- Responsive styles that adapt to different screen sizes
This exercise will help you apply the concepts covered in this tutorial to create a well-styled, themeable Next.js application.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)