Why do we use .module.css

If you ever worked with React, you might have noticed the use of Component.module.css for styling the Component.jsx instead of regular Component.css . We'll discuss why.

If regular css files are used, the styles will apply to a global scope. Globally, all the elements having the specific selector will have the styles applied.

Example:

Both components A and B have a div component with className "text" .

A.css defines a style rule that sets the color of the "text" selector to red. B.css defines a style rule that sets the color of the "text" selector to blue.

A.css

.text{
    color: red;
}

B.css

.text{
    color: blue;
}

A.jsx

import styles from "./A.css";

function A() {
  return <div className="text">A</div>;
}

export default A;

B.jsx

import styles from "./B.css";

function B() {
  return <div className="text">B</div>;
}

export default B;

Result: Both div components are coloured blue.

Reason: Style set by B.css for selector "text" is applied globally for all elements with "text" selector.

Is this what we wanted? No. We want A to be in red and B to be in blue. To avoid this problem we need to make the scope local. CSS modules let us do this.


CSS modules do not have an official specification nor are they a browser feature. They are part of a compilation process that executes against your project to convert scoped classes and selectors into CSS files that the browser can parse and understand. Read more

Bundlers like Create React App, Vite perform the compilation and generate unique class names.

Modified Example:

Rename the css files with .module.css extension.

A.jsx

import styles from "./A.module.css";

function A() {
  return <div className={styles.text}>A</div>;
}

export default A;

B.jsx

import styles from "./B.module.css";

function B() {
  return <div className={styles.text}>B</div>;
}

export default B;

Result :

Reason:
Each module generate unique className . Therefore encapsulation is achieved by limiting the scope to modules.

If we inspect the webpage, we can see the className being unique across the modules.

Yeah that's what we wanted! <3