CSS Modules for Scoped Component Styling
CSS Modules for Scoped Component Styling
1. The Need for Scoped CSS
As applications grow to hundreds of components, global CSS namespace collisions become inevitable. You want the flexibility of writing pure, clean CSS with full support for pseudo-classes, media queries, and animations—without the fear that your classes will accidentally leak or clash with other components.
CSS Modules solve this problem elegantly. A CSS Module is a CSS file where all class names and animation names are scoped locally to the component by default.
Vite supports CSS Modules out of the box with zero configuration required!
2. Naming Convention: [name].module.css
To inform Vite and your bundler that a stylesheet is a CSS Module, simply name the file with the .module.css extension:
3. How CSS Modules Work
In your CSS Module, write standard, clean CSS classes:
In your React component, import the styles as an object:
4. Under the Hood: Class Name Hashing
When Vite processes Badge.module.css, it automatically transforms every class name into a unique, hashed string:
Because the compiled class names include unique hashes derived from the file path and component name, it is mathematically impossible for .badge in Badge.module.css to collide with .badge in UserCard.module.css!
Practice Quiz
:hover and media queries inside CSS Modules?.badge-primary) in JSX?Utility-First Styling with Tailwind CSS in React
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| CSS Stylesheets and Global Class Names | Utility-First Styling with Tailwind CSS in React |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.