nextjs
  1. nextjs-using-css-modules

Next.js Using CSS Modules

Syntax

/* Styles.module.css */

.className {
  /* Styles for the element with class "className" */
}
import styles from './Styles.module.css';

function Component() {
  return (
    <div className={styles.className}>
      {/* Content */}
    </div>
  )
}

Example

/* MyComponent.jsx */

import styles from './MyComponent.module.css';

function MyComponent() {
  return (
    <div className={styles.container}>
      <h1 className={styles.heading}>Welcome to My Component</h1>
      <p className={styles.text}>This is some text inside my component</p>
    </div>
  )
}

export default MyComponent;

/* MyComponent.module.css */

.container {
  background-color: #f0f0f0;
  padding: 20px;
  border-radius: 10px;
}

.heading {
  font-size: 32px;
  font-weight: bold;
}

.text {
  font-size: 16px;
  line-height: 1.4;
}

Output

The output of the above example will be a component with a container, heading, and text element that are styled with unique CSS classes.

Explanation

Next.js is a popular framework for building React applications with server-side rendering. CSS Modules offer a way to style components in a modular and reusable way. CSS Modules create unique class names for each module and map those names to the corresponding HTML elements.

Use

Using CSS Modules in Next.js is a great way to keep your code modular, organized, and easier to maintain. You can create unique styles for each component and reuse those styles across your application without worrying about naming conflicts.

Important Points

  • CSS Modules are a way to use CSS in a modular and reusable way.
  • CSS Modules create unique class names for each module to avoid naming conflicts.
  • In Next.js, you can import styles using the import styles from './Styles.module.css' syntax.
  • You can apply unique styles to each component using the className={styles.className} syntax.
  • CSS Modules can help make your code more modular, organized, and easier to maintain.

Summary

Using CSS Modules in Next.js is a powerful way to keep your code organized and maintainable. By creating unique class names for each module, you can avoid naming conflicts and reuse styles across your application. Understanding how to use CSS Modules is an important part of building scalable and maintainable Next.js applications.

Published on: