Part 9: Styling Your Next.js Application with Global CSS
[Pages] Styling

In our journey of building a Next.js application, we've reached an exciting milestone: adding styles to enhance the visual appeal of our app. So far, our pages have been relying on default browser styles, which may not be the most attractive. Let's dive into styling by creating a global CSS file to give our application a polished look.
Why Use Global CSS?
Global CSS allows you to define styles that apply across your entire application. This approach is perfect for setting base styles, like fonts and colors, that maintain consistency throughout your site.
Step 1: Setting Up Global CSS
To organize our styles, we'll create a dedicated folder for CSS files.
Creating the CSS File
Create a Styles Folder: At the root of your project, create a folder named
styles.Create a Global CSS File: Inside the
stylesfolder, create a file namedglobals.css.
Adding Basic Styles
Let's add some basic CSS rules to globals.css:
/* File: styles/globals.css */
body {
font-family: Arial, Helvetica, sans-serif;
}
a {
color: darkred;
text-decoration: none;
}
a:focus, a:hover {
text-decoration: underline;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline;
}
li:not(:first-child) {
margin-left: 0.75rem;
}Understanding the Styles
Font Family: Sets a sans-serif font for the entire body, ensuring text is easy to read.
Link Styling: Changes link color to dark red and removes underlines, adding them back on hover or focus for better user feedback.
Navigation Bar: Removes bullet points from lists, aligns links horizontally, and adds spacing for readability.
Step 2: Applying Global Styles
To make these styles active, we need to import globals.css into our custom App component.
Modifying the App Component
Open your _app.js file and import the global CSS:
// File: pages/_app.js
import NavBar from '../components/NavBar';
import '../styles/globals.css';
function App({ Component, pageProps }) {
return (
<>
<NavBar />
<Component {...pageProps} />
</>
);
}
export default App;Key Points
CSS Import: By importing
globals.cssin_app.js, the styles are applied across all pages of your application.Flexible Structure: You can import multiple CSS files if needed; the naming is arbitrary as long as it reflects the purpose of the styles.
Conclusion
By leveraging global CSS in Next.js, we've transformed the appearance of our application with just a few lines of code. This approach provides a solid foundation for consistent styling across your site. As you continue to develop your app, you'll likely want to explore component-level styles for more granular control, which we'll cover in future posts. Until then, happy styling!
Last updated