CSS Modules: Scoped Class Names
Enable CSS Modules in a Vite or webpack project to auto-scope class names to the component file and eliminate global style leaks.
What Are CSS Modules?
CSS Modules transform class names at build time to include a unique hash, scoping them to the component file. A class named .card becomes .card_a1b2c3 — impossible to accidentally collide with other components' styles.
How CSS Modules Work
Import the CSS file as an object. Use the object's properties as class names. Bundlers (Vite, webpack) handle the transformation.
// Button.module.css
.button {
background: #6366f1;
color: white;
padding: 8px 16px;
}
.button--large {
padding: 12px 24px;
}
// Button.tsx
import styles from './Button.module.css';
function Button({ large }: { large?: boolean }) {
return (
<button className={`${styles.button} ${large ? styles['button--large'] : ''}`}>
Click me
</button>
);
}All lessons in this course
- BEM Methodology: Block Element Modifier
- CSS Modules: Scoped Class Names
- CSS-in-JS: Styled-components and Emotion
- Tailwind CSS Utility-First Approach