Assets, Metadata, and CSS

Layout Component

First, Let’s create a Layout component which will be shared across all pages.

  • Create a top-level directory called components.
  • Inside, create a file called layout.js with the following content:
export default function Layout({ children }) {
  return <div>{children}</div>

Then, in pages/posts/first-post.js, import Layout and make it the outermost component.

import Head from 'next/head'
import Link from 'next/link'
import Layout from '../../components/layout'

export default function FirstPost() {
  return (
        <title>First Post</title>
      <h1>First Post</h1>
        <Link href="/">
          <a>Back to home</a>

Adding CSS

Now, let’s add some styles for Layout. To do so, we’ll use CSS Modules, which lets you import CSS files in a React component.

Create a file called layout.module.css in the components directory with the following content:

.container {
  max-width: 36rem;
  padding: 0 1rem;
  margin: 3rem auto 6rem;

Important: To use CSS Modules, the CSS file name must end with .module.css.

To use this container class inside layout.js, you need to:

  • Import the file as styles
  • Use styles.container as the className
import styles from './layout.module.css'

export default function Layout({ children }) {
  return <div className={styles.container}>{children}</div>

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 tag 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.

Quick Review: Which of the following styling methods does Next.js not have built-in support for?