Sub topic 1
Why global CSS gets hard to maintain
A React component keeps its markup, state and behavior in one file, but plain CSS does not follow it there. Every rule you write lands in one browser-wide namespace. This chapter explains what that costs as an application grows. It also sets up the problem that CSS Modules solve in the chapters that follow.
Prerequisites
This chapter assumes you already know:
- Basic React: function components, props and JSX.
- CSS fundamentals: selectors, the cascade and specificity.
- ES module imports (
import x from './file'). - How a bundler such as Vite, webpack or Next.js turns your source files into files the browser loads.
You do not need any CSS Modules knowledge yet.
CSS has one global scope
A stylesheet is not tied to the file that imports it. When the browser applies a rule such as .title { color: red; }, it checks every element on the page. It does not ask which component the rule came from.
In a React project, you often write this:
import './Card.css';
export function Card({ heading, children }) {
return (
<section className="card">
<h2 className="title">{heading}</h2>
{children}
</section>
);
}The import './Card.css' line only tells the bundler to include the file. After bundling, the rules join all other CSS in the page's stylesheets. The import looks like a dependency between the component and its styles, but the browser never sees that link. It sees one pool of rules and one pool of elements.
Problem 1: name collisions
Suppose two developers build two components in different weeks. Each picks the obvious class name title.
/* Card.css */
.title {
font-size: 1.25rem;
font-weight: 700;
color: #111827;
}/* Alert.css */
.title {
font-size: 0.875rem;
text-transform: uppercase;
color: #b91c1c;
}import './Card.css';
import './Alert.css';
export function Dashboard() {
return (
<main>
<section className="card">
<h2 className="title">Revenue</h2>
</section>
<div className="alert">
<strong className="title">Payment failed</strong>
</div>
</main>
);
}Both .title rules have the same specificity (one class selector). When two rules conflict, the one that appears later in the final stylesheet wins. Here the card heading gets text-transform: uppercase and red text from the alert, because Alert.css comes later. It also keeps the card's font-weight: 700 and gets the alert's smaller font size. The result is a mix of two rule sets that neither author intended.
Nothing warns you about this. No error, no lint failure, no type check. You find it by looking at the screen.
Problem 2: the order of rules decides the result
Because specificity ties are broken by source order, the outcome depends on which file the bundler emits first. That order is not something you set deliberately.
- In development, a bundler may inject style tags in the order modules are first imported.
- In production, the bundler may merge CSS into one or several files, and its ordering can differ from development.
- With code splitting, a route loaded later can add rules after the user has already seen the page. A rule that lost to another rule at first load can start winning after a navigation.
This produces bugs of the form "it looks right locally but wrong in production", or "it broke after I changed an unrelated import". A reordered import line changes your visual output, and nobody reads import order as a styling decision.
Problem 3: specificity escalation
Once collisions appear, the common fix is to make your selector more specific so it wins.
.card .title {
color: #111827;
}
.alert .title {
color: #b91c1c;
}This works, but each fix raises the specificity needed by the next one. Teams then reach for longer selector chains, element selectors like main section.card h2.title, or !important.
.sidebar .card .title {
color: #111827 !important;
}Every escalation makes the stylesheet harder to override, and now the card's styles depend on its location in the DOM. Moving Card out of .sidebar silently drops its styles. Reusing it somewhere else requires either duplicating the rules or adding another, more specific selector.
Problem 4: deleting CSS is unsafe
When you remove a component, can you remove its CSS? In a global setup, you have to search the whole code base for every use of .title, in JSX, in other CSS files, in tests, and in strings built at runtime like ` title-${size} `. If you miss a use and delete the rule, something breaks. If you are unsure, you leave the rule in place.
Stylesheets in long-lived projects therefore only grow. Dead rules accumulate and look just like live ones. Each time someone edits CSS they must check a large unknown set of elements that might be affected. This is the maintainability cost: you cannot reason about a change locally.
Problem 5: leaking in both directions
Global CSS leaks in two directions:
- Outward: your component's rules affect elements you never intended to style. A rule like
h2 { margin: 0; }written for one component changes everyh2on the page. - Inward: someone else's rules, including a third-party library's CSS or a global reset, can change your component. A component cannot defend itself, because it does not own its own styles.
The following snippet shows the outward case. It looks harmless in a component file but is global:
/* Sidebar.css */
ul {
list-style: none;
padding: 0;
}
a {
color: inherit;
}Every list and every link in the app now loses its bullets, padding and link color. Components built later may have to undo these rules.
Conventions people use, and their limits
Teams have long worked around these problems with discipline. These approaches help, but each has a cost.
| Approach | How it helps | Limitation |
|---|---|---|
| Naming convention such as BEM (`card__title`, `alert__title`) | Makes names unique by hand | Relies on every developer following it. Names get long, and nothing enforces uniqueness |
| Prefixing by component or team (`dash-card-title`) | Reduces collisions between teams | Same enforcement problem. Prefixes can still collide |
| Single shared stylesheet owned by one team | Gives one place to check for conflicts | Becomes a bottleneck and grows without limit |
| Utility classes (Tailwind and similar) | Avoids writing custom rules and names | A different workflow. It does not suit teams that want regular CSS |
| CSS-in-JS libraries | Scope styles to components | Often adds a runtime library and extra JavaScript, depending on the library |
All of these either depend on humans being consistent or change the way you write styles. A tool that makes uniqueness automatic, while keeping ordinary CSS files, would remove the root problem.
What CSS Modules change
CSS Modules keep ordinary CSS syntax but change how class names work. A file named Card.module.css is processed at build time. Each class name in it is rewritten to a unique generated name, and the import gives your JavaScript a mapping from your original name to the generated one. With that, .title in Card.module.css and .title in Alert.module.css can never collide, because they become different names such as Card_title__x7Qa1 and Alert_title__k9Zp2. The exact format depends on your bundler settings.
The rest of this tutorial covers how that works, how to apply and combine classes, and how to handle the cases where you do want global behavior. For now, keep these points in mind:
- The scoping happens at build time, so there is no runtime library to ship.
- You still write CSS, with the same selectors, media queries and properties.
- Scoping only covers class names (and IDs). It does not remove the cascade or specificity, so an element selector such as
ul { ... }in a module file is still global. A later chapter returns to this.
Checking your own project
Before moving on, you can estimate how exposed a codebase is to the problems above. Look for these signs:
- Many
!importantdeclarations. - Selectors that are three or more levels deep and rely on DOM structure.
- Class names that are short and generic, such as
title,container,wrapper,button. - Files nobody wants to delete rules from.
- Visual bugs that appear only after a build or only on certain routes.
The more of these you find, the more you gain from scoping styles per component.
Exercise
Two components each define .title in separate CSS files, and both are used on the same page. Which rule's declarations apply, and why is this fragile?
Show answer
Both rules have equal specificity, so the one that appears later in the final bundled stylesheet wins wherever the two conflict. Properties that only one rule sets still apply. This order comes from import order and bundler behavior, so reordering imports or splitting code differently can change the page's appearance with no error.
Exercise
A teammate fixes a collision by changing .title to .sidebar .card .title and adding !important. Name two maintenance problems this creates.
Show answer
The rule now depends on the card being inside .sidebar, so moving the component drops its styles. It also raises the specificity that any later override must beat, which pushes the team toward more !important and longer selectors.
Exercise
Why is it unsafe to delete a CSS rule for a removed component in a large global stylesheet?
Show answer
The class name may be used elsewhere, in other components, other CSS files, tests, or class names built from strings at runtime. Because any rule can match any element, you cannot tell from the stylesheet alone which elements depend on it.