Course contentsShow
← Web Development
Lesson 601 of 2,98210. Typography and Design SystemsFree lesson

CSS Modules and Scoped Styles

Using build tools to automatically scope CSS to components, preventing global namespace pollution.

CSS Modules and Scoped Styles

You'll learn: How build tools automatically scope CSS to individual components, preventing class name conflicts across your entire application.

The Global Namespace Problem

By default, all CSS lives in one giant global pool. If you write .button in one file and .button in another, they collide and override each other—just like naming two functions the same thing in JavaScript. As projects grow, avoiding naming conflicts becomes exhausting.

What Are CSS Modules?

CSS Modules are a build-time solution that automatically generates unique class names for your styles. You write normal CSS, but the build tool (like Webpack, Vite, or Parcel) transforms your human-readable class names into unique identifiers.

How It Works

You write:

/* Button.module.css */
.button {
  background: blue;
  padding: 1rem;
}

The build tool transforms it to something like:

.Button_button__xj2k9 {
  background: blue;
  padding: 1rem;
}

When you import this CSS file into your component, you receive an object mapping your original names to the unique versions:

// The build tool handles the import
const styles = { button: 'Button_button__xj2k9' };

The Analogy

Think of CSS Modules like apartment buildings versus shared dorm rooms. Without scoping, everyone shares one messy common space (global styles). With CSS Modules, each component gets its own private apartment—you can name things whatever you want inside without worrying about conflicts with neighbors.

Benefits

  • No naming collisions between components
  • Local reasoning — styles are tied to specific components
  • Safe refactoring — deleting a component removes its styles
  • Still just CSS — no special syntax to learn

Key Takeaway: CSS Modules use build tools to automatically namespace your styles to specific components, eliminating global conflicts while keeping your CSS syntax familiar and clean.