Layout Component
First, let’s create a Layout component which will be shared across all pages.
- Create a top-level directory called
components
. - Inside
components
, create a file calledlayout.js
with the following content:
Then, open pages/posts/first-post.js
, add an import for the Layout
component, and make it the outermost component:
Adding CSS
Now, let’s add some styles to the Layout
component. To do so, we’ll use CSS Modules, which lets you import CSS files in a React component.
Create a file called components/layout.module.css
with the following content:
Important: To use CSS Modules, the CSS file name must end with
.module.css
.
To use this container
class inside components/layout.js
, you need to:
- Import the CSS file and assign a name to it, like
styles
- Use
styles.container
as theclassName
Open components/layout.js
and replace its content with the following:
If you go to http://localhost:3000/posts/first-post now, you should see that the text is now inside a centered container:
Automatically Generates Unique Class Names
Now, if you take a look at the HTML in your browser’s devtools, you’ll notice that the div
rendered by the Layout
component has a class name that looks like layout_container__...
:
This is what CSS Modules does: It automatically generates unique class names. As long as you use CSS Modules, you don’t have to worry about class name collisions.
Furthermore, Next.js’s code splitting feature works on CSS Modules as well. It ensures the minimal amount of CSS is loaded for each page. This results in smaller bundle sizes.
CSS Modules are extracted from the JavaScript bundles at build time and generate .css
files that are loaded automatically by Next.js.