Introduction to Global Styles and Themes

Global styles and themes are an essential part of maintaining a consistent design across your Next.js application. Global styles can be used for styling elements that should have a uniform appearance, like fonts and layout. Themes allow you to manage colors, fonts, and other design tokens. In this tutorial, we'll explore how to add global styles and themes to your Next.js app.


Adding Global Styles

1. To add global styles to your Next.js app, create a CSS file and import it in your application's entry point (e.g., _app.js or index.js). For example:


/* global-styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}


// pages/_app.js
import '../styles/global-styles.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;

The global-styles.css file contains styles that apply globally to the entire app, such as setting the font family and background color.


Implementing Themes

2. To implement themes in Next.js, create a theme configuration file. For example, create a theme.js file:


// theme.js
const theme = {
colors: {
primary: 'blue',
secondary: 'green',
},
fonts: {
body: 'Arial, sans-serif',
heading: 'Helvetica, sans-serif',
},
};
export default theme;

In this example, we define a theme object with colors and fonts.

3. Import the theme in your components and use it to style elements:


// MyComponent.js
import React from 'react';
import theme from '../theme';
const MyComponent = () => {
return (
<div>
<h2 style={{ color: theme.colors.primary }}>Styled Component</h2>
<p style={{ fontFamily: theme.fonts.body }}>This component uses a theme.</p>
</div>
);
};
export default MyComponent;

By importing the theme object, you can access the defined colors and fonts and apply them to your components.