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.
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:
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;
}
Next, import the CSS module into your .js or .jsx files like so:
import styles from './style.module.css'
You can now use the styles defined as properties of the imported styles
object.
<div className={styles.container}>
<p>Hello World!</p>
</div>
/* 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.
/* 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.
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.
Remember, practice is key to mastering any concept. Happy coding!