What Are CSS Modules
You'll learn: What CSS Modules are and how they solve the problem of CSS class name conflicts by creating locally scoped styles at build time.
The Global Namespace Problem
By default, CSS is global. Every class name you write — whether it's .button, .card, or .header — exists in one giant shared namespace. This means a .button class in your navigation component can accidentally clash with a .button class in your footer, causing unexpected styling issues.
Think of it like everyone in a town having the same address system. If two families both claim "123 Main Street," mail gets delivered to the wrong house!
CSS Modules: Build-Time Scoping
CSS Modules is a build-time solution that automatically transforms your class names into unique identifiers. When you write .button in your component's CSS Module file, it gets compiled into something like .Header_button__3xk2d — a unique name that won't collide with any other component's styles.
The magic happens during your build process (using tools like webpack, Vite, or Parcel). You write normal-looking CSS, but the build tool rewrites both your stylesheets and your JavaScript imports to use these generated unique names.
How It Works in Practice
You import your CSS Module file as a JavaScript object, and reference class names through that object. The build tool handles the transformation automatically, ensuring that what you write in CSS matches what gets applied in your HTML — just with those uniquified names.
This approach gives you locally scoped styles by default, eliminating global namespace pollution without requiring runtime JavaScript or complex naming conventions like BEM.
Key Takeaway: CSS Modules solve global namespace pollution by transforming class names into unique identifiers at build time, giving you automatic local scoping without changing how you write CSS or requiring complex naming conventions.