Styling a Next.js app
There are two ways in which you can apply styling to your Next.js app using CSS. The first is by using a global stylesheet, which is applied to every page and component in your app. The second way is by using CSS modules, which apply styling to specific components only.
In our template app we already have a styles folder under our root directory which has two stylesheets – globals.css
and Home.module.css
. The Home.module.css
contained all the styles for the default template page so that file can be deleted.
Global stylesheet
The template we’re using comes with a global stylesheet which is already being used and has been imported in pages/_app.js
.
Let’s add a couple of extra styles to our globals.css
to see how it works.
Now modify layout.js
to make use of those two styles and check if they apply in our dev environment.
Module stylesheets
Module stylesheets can be imported anywhere in your app on a page by page or component by component basis. At this stage we’ll create two modules to store the CSS for the header component and the footer component.
In the styles folder, add a new file named Header.module.css
and copy this CSS into it.
We then need to import this module into the header.js
so that we can use the stylesheet.
In our stylesheet we’ve declared the styles for the id site_title
and applied that style to the site title in the header.js file.
We’ll then do the same for the footer creating a Footer.module.css
file and adding the following code.
Again, we can import this stylesheet into the footer.js
file and apply the styles using the following code:
If we take a look at our app now in the browser, the styles defined in Header.module.css and Footer.module.css will be applied to the header and footer components respectively.
We haven’t added much in the way of styles so far but as we add extra things to the headers in future we’ll start filling out these stylesheets. Next time we’ll do just that as we look at adding additional pages and link to them from the navigation bar in our header.