DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is CSS Modules in React? Difference between Normal CSS and CSS Modules in React?

CSS Modules is a CSS styling technique in React that allows us to write CSS for individual components.

It automatically creates unique class names to avoid CSS conflicts between components.

In simple words, CSS Modules prevent one component's CSS from affecting another component.

import React from 'react';
import styles from './Home.module.css';

function Home() {
return (



Welcome to React

  <button className={styles.button}>
    Click Me
  </button>
</div>

);
}

export default Home;

Main Advantages:

  1. Avoids CSS conflicts.
  2. Provides component-level styling.
  3. Makes code easier to maintain.
  4. Keeps styles separate for each component.
  5. Automatically generates unique class names.

Both are used to style React components, but the main difference is how CSS class names are managed.

  1. Comparison:

Normal CSS CSS Modules
Uses global class names. Uses locally scoped class names.
Styles can conflict. Prevents class name conflicts.
Uses className="title". Uses className={styles.title}.
Imported as a normal CSS file. Imported as a CSS Module file.
File extension: .css File extension: .module.css

Normal CSS:
App.css

import './App.css';

function App() {
return

Hello React

;
}

export default App;

CSS Modules:
App.module.css

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

function App() {
return

Hello React

;
}

export default App;

Top comments (0)