Assets, Metadata, and CSS

Layout Component

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

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

export default Layout

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 (
    <Layout>
      <Head>
        <title>First Post</title>
      </Head>
      <h1>First Post</h1>
      <h2>
        <Link href="/">
          <a>Back to home</a>
        </Link>
      </h2>
    </Layout>
  )
}

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 this CSS Modules, the CSS file name must end with .module.css.

To use this in Layout, you need to:

  • Import it as styles
  • Use styles.<class-name> as className
  • In this case, the class name is container, so we’ll use styles.container
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.