Back to results for “Styled Components & Tailwind)”
React › Styling in React (CSS Modules, Styled Components & Tailwind)

What are CSS Modules and how do they prevent class names from clashing between components?

Beginner

Answer

A CSS Module is a regular CSS file where every class name is automatically made unique behind the scenes during the build process, so a class name like button used in one component's CSS file never accidentally conflicts with a class of the same name used in a completely different component.
/* Button.module.css */
.button {
  background-color: blue;
  color: white;
}

// Button.js
import styles from './Button.module.css';

function Button() {
  return <button className={styles.button}>Click Me</button>;
}
Real-world example A large app with dozens of components each has their own small CSS Module file, safely reusing common class names like container or title everywhere without ever worrying about accidental style conflicts.

Common follow-ups: How does a CSS Module actually make class names unique behind the scenes?;Can you share common styles between two different CSS Modules?