What are CSS Modules and how do they prevent style collisions?
· Category: HTML & CSS
Short answer
CSS Modules are CSS files in which all class names are scoped locally to the component that imports them. A build tool hashes the class names so they do not collide with global styles.
How it works
When you import a CSS Module into a component, the classes become a JavaScript object mapping human-readable names to generated unique names. Only the component that imports the module receives those styles.
Example
/* Button.module.css */
.primary { background: blue; color: white; }
.large { padding: 1rem 2rem; }
import styles from './Button.module.css';
function Button({ size }) {
return (
<button className={`${styles.primary} ${styles[size]}`}>
Click me
</button>
);
}
Why it matters
CSS Modules eliminate the need for strict naming conventions like BEM while preserving the benefits of scoped styles. They integrate naturally with React, Vue, and other component-based frameworks without requiring a CSS-in-JS library.