Sub topic 1
Why Global CSS Gets Hard to Maintain
Prerequisites
This chapter assumes you know basic React components, props, and JSX. You should also understand CSS selectors, the cascade, specificity, and ES module imports. A bundler such as Vite, webpack, or Next.js is assumed.
Why Global CSS Gets Hard to Maintain
Global CSS applies across the whole document. A class such as .button can affect every element using that name, including elements in unrelated components.
.button {
padding: 0.5rem 1rem;
background: blue;
}As an application grows, developers often add names such as .card, .title, or .active. Names collide, and later rules can override earlier rules through the cascade. Developers then add prefixes, increase selector specificity, or track which stylesheet owns each class.
Global styles also make deletion risky. Removing a rule from one feature can break another feature that happens to use the same class.
What CSS Modules Give You
CSS Modules provide local scoping for class names. A stylesheet is treated as a module when its filename ends with .module.css. The bundler transforms each local class into a generated, unique name at build time.
flowchart TD
A["Button.module.css"] --> B["Bundler"]
B --> C["Unique generated class name"]
C --> D["Rendered button"]The component still uses ordinary CSS, but the class name is limited to components that import the module. CSS Modules do not add a runtime styling library. They create a mapping during the build.
Creating and Importing a `.module.css` File
Create Button.module.css beside the component:
.button {
padding: 0.5rem 1rem;
border: 0;
border-radius: 4px;
background: #2563eb;
color: #fff;
cursor: pointer;
}
.button:hover {
background: #1d4ed8;
}Import the file as a default import. The imported value is an object whose keys are the local class names.
import styles from './Button.module.css';
export function Button({ children }) {
return <button className={styles.button}>{children}</button>;
}Applying Classes Through the `styles` Object
styles.button returns the generated class name for .button. The JSX className prop applies that value to the element.
Class names with hyphens require bracket notation:
<div className={styles['menu-item']}>Profile</div>Treat generated names as implementation details. Use stable semantic selectors, accessible roles, or visible text in tests instead of asserting the generated class string.
Exercise
What does styles.button represent in a React component?
Show answer
It is the generated class-name string mapped from the local .button class in the imported CSS Module.