Gatsby
Up and Running with Gatsby: Styling

CSS Modules

PRO

Let's learn about CSS Modules.

We talked in the last video about why scoped CSS would be really nice. It's easier to maintain, cleaner to write, and prevents naming conflicts.

There are a couple of ways to get scoped CSS in Gatsby. The first is called CSS modules. A CSS Module is a CSS file in which all class names are scoped locally by default. Gatsby supports CSS modules out of the box.

Let's use a CSS module with the NavBar. First, create a file under src/components called navbar.module.css.

Cut and paste the nav-link class we made in the global styles.css file into navbar.module.css. We're going to rename this class to camel case to make importing it easier:

.navLink {
   font-family: Verdana, Helvetica, sans-serif;
    font-size: 1.2rem;
    padding: 0.8rem;
    text-decoration: none;
}

Now, back in NavBar.js, import the styles from the module:

import navBarStyles from "./navbar.module.css"

It's sort of a convention of CSS modules to tack Styles onto the end of the name of the styles, but we could call this whatever we want.

To use the imported styles, change the className input to className={navBarStyles.navLink} on each link.

If you refresh the page, you should be able to see your navLink class in action! When you inspect the link tag, you should see something like navbar-module--navLink--vqJ05 as the class. This is how CSS modules scopes CSS; it generates a unique class name using the module and a random series of characters. Even if we were to create a different navLink class in another module, the two wouldn't conflict. Pretty awesome!

Let's do a quick assignment about CSS modules.