gitmyhub

css-modules-demos

JavaScript ★ 395 updated 10y ago

a collection of simple demos of CSS Modules

CSS Modules Demos

This repository is a collection of working examples that teach you how to use CSS Modules — a technique that solves a common problem in web development: CSS class names accidentally colliding and overriding each other across different parts of your application.

Normally, when you write CSS, every class name you create is global, meaning it can affect HTML elements anywhere on your page. If two different components use the same class name, they'll interfere with each other. CSS Modules fixes this by automatically converting your class names into unique, randomly-generated strings that are specific to each component. So instead of a class called .title, the build process turns it into something like ._3zyde4l1yATCOkgn-DBWEL. This means you can use simple, readable names in your code without worrying about conflicts.

The repository contains six progressive demos, each showing a different feature. Demo01 shows the basic idea of local scoping. Demo02 explains how to explicitly create global classes when you actually need them. Demo03 demonstrates customizing how those random class names are generated. Demo04 teaches "composition," where one CSS class inherits styles from another. Demo05 shows how to reuse styles by importing from other CSS files. Demo06 covers variables in CSS — a way to define values once and reuse them throughout your stylesheets.

Each demo is runnable: you clone the repository, install dependencies, then run commands like npm run demo01 to see a working example in your browser. The README walks through the code for each example, showing both the CSS and the JavaScript (using React), plus explaining what the build tool does behind the scenes.

This is useful for developers building web applications who want to understand how modern projects avoid CSS conflicts without writing overly complex class names. It's particularly relevant if you're learning React or working in a larger codebase where multiple developers are writing CSS.