Working with CSS Modules in Next.js

Tutorial 4 of 5

Working with CSS Modules in Next.js

1. Introduction

This tutorial focuses on demonstrating the usage of CSS Modules in Next.js. By the end of this tutorial, learners will be capable of creating and importing CSS Modules in their Next.js applications, thus preventing conflicts and overlapping styles.

Prerequisites

  • Basic understanding of React.js
  • Basic knowledge of CSS
  • Familiarity with Next.js will be beneficial

2. Step-by-Step Guide

CSS Modules is a CSS file in which all class names and animation names are scoped locally by default. This feature allows you to use the same CSS class name in different files without worrying about naming clashes.

To use CSS Modules in Next.js, you need to follow these steps:

Step 1: Creating a CSS Module

Create a CSS file with the extension .module.css. For instance, you can create a file named style.module.css

/* style.module.css */
.container {
  margin: 20px;
  padding: 20px;
  border: 1px solid black;
}

Step 2: Importing the CSS Module

Next, import the CSS module into your .js or .jsx files like so:

import styles from './style.module.css'

Step 3: Using the CSS Module

You can now use the styles defined as properties of the imported styles object.

<div className={styles.container}>
  <p>Hello World!</p>
</div>

3. Code Examples

Example 1: Basic Usage of CSS Module

/* styles.module.css */
.text {
  color: red;
  font-size: 20px;
}
// MyComponent.jsx
import styles from './styles.module.css'

const MyComponent = () => (
  <div className={styles.text}>Hello, Next.js!</div>
)

In this example, the text within the MyComponent component will be red and of font size 20px.

Example 2: Composing Multiple Classes

/* styles.module.css */
.text {
  color: red;
}

.big {
  font-size: 30px;
}
// MyComponent.jsx
import styles from './styles.module.css'

const MyComponent = () => (
  <div className={`${styles.text} ${styles.big}`}>Hello, Next.js!</div>
)

In this example, we merged two classes using a template string. As a result, the text will be red and have a font size of 30px.

4. Summary

This tutorial covered the basics of creating and using CSS Modules in Next.js. The next steps would be to explore more complex CSS features such as media queries and animations with CSS Modules.

5. Practice Exercises

  1. Create a CSS Module that sets the background color of a div.
  2. Create a CSS Module that changes the font size and color of a paragraph text.
  3. Compose multiple classes from different CSS Modules.

Remember, practice is key to mastering any concept. Happy coding!

Further Reading