Sub topic 1
Why CSS gets hard to maintain at scale
Prerequisites
This chapter assumes you already know:
- CSS selectors, properties and the box model.
- The basics of the cascade, inheritance and specificity.
- How to link a stylesheet to an HTML page.
- Basic command-line and npm usage, which later chapters need for tooling.
You do not need any experience with BEM, build tools or cascade layers. Later chapters introduce them as answers to the problems described here.
The core problem: CSS is global
A small site with one stylesheet and a few pages rarely causes trouble. The trouble starts when many people edit the same files over several years.
CSS has no built-in notion of ownership. Every rule in every loaded stylesheet can match any element on the page. A rule written for the checkout page can change the footer. A rule you delete can break a page you forgot existed.
This leads to a common pattern:
- A developer needs to change one element.
- They cannot tell what else the rule affects.
- They add a new, more specific rule instead of editing the old one.
- The stylesheet grows, and the next developer faces the same doubt.
Over time, the code becomes append-only. Nobody removes anything because nobody can prove it is unused.
Three forces behind the problems
Most scaling problems come from three mechanisms working together: global scope, specificity and source order.
Global scope
Class names live in one shared namespace. Two developers can pick the same name for different purposes.
/* components/card.css, written by team A */
.title {
font-size: 1.25rem;
margin-bottom: 0.5rem;
}/* pages/report.css, written by team B */
.title {
font-size: 2rem;
text-transform: uppercase;
}If both files load on the same page, every element with class="title" receives both sets of declarations. Where they conflict, the rule that comes later wins. Neither author did anything wrong in isolation. The collision only appears when the two files meet.
Specificity
Specificity decides which rule wins when several rules match one element and set the same property. It is compared as three counts, written (IDs, classes and attributes and pseudo-classes, elements and pseudo-elements). The highest count in the leftmost column wins.
| Selector | Specificity |
|---|---|
| `p` | 0,0,1 |
| `.note` | 0,1,0 |
| `.sidebar .note` | 0,2,0 |
| `nav ul li a.active` | 0,1,4 |
| `#main .note` | 1,1,0 |
| `style="..."` attribute | beats all selectors |
| `!important` | beats normal declarations |
Specificity is useful. It becomes a problem when developers use it as a weapon. Suppose a component style is hard to override:
#sidebar .widget .title {
color: #333;
}To change the color somewhere, you now need a selector with at least the same weight and a later position, or you reach for !important:
.title {
color: crimson !important;
}That fixes one case. It also adds a rule that only another !important with higher specificity can beat. This is a specificity arms race, and each step makes the next override harder.
Source order
When two rules have equal specificity, the one that appears later in the cascade wins. This means the result depends on the order in which stylesheets load.
<link rel="stylesheet" href="components.css">
<link rel="stylesheet" href="utilities.css">If a utility class and a component class have the same specificity, utilities.css wins because it comes later. Swap the two lines and the page looks different, though no CSS changed.
Order also changes in less obvious ways:
- A bundler may concatenate files in a different order than you expect.
- Code splitting may load a route's stylesheet after a shared one on one navigation path and before it on another.
- Lazy-loaded components inject
<style>or<link>elements at the end of the document, after your base styles.
The same code can then render differently depending on how the user reached the page.
How the three forces interact
The three forces reinforce one another. Global scope makes accidental matches likely. Specificity is the usual tool for fixing a match. Source order decides the leftover ties, and it is the hardest of the three to see in a code review.
The diagram below shows the cycle.
Symptoms to recognize
You can spot a codebase in this state by several signs.
- Rules that exist only to undo other rules. Examples are
margin: 0orcolor: inheritrepeated across files. - Selectors tied to document structure. For example
.page > div:nth-child(2) ul li a. A markup change breaks the style. - ID selectors and
!importantin ordinary components. They signal that earlier overrides lost. - Fear of deletion. Dead rules stay because nobody can prove they are unused.
- Unpredictable load order. Reordering
<link>tags or imports changes the appearance. - Duplicated values. The same hex color or spacing value appears in dozens of places, so a rebrand needs a risky search and replace.
- Large stylesheets. Every page downloads CSS for every other page.
A worked example: a style leak
Here is a realistic leak. A team adds a generic rule for lists in articles.
/* article.css */
ul li {
list-style: disc;
margin-left: 1.5rem;
}Later, another team builds a navigation menu.
<nav class="menu">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/docs">Docs</a></li>
</ul>
</nav>/* menu.css */
.menu li {
display: inline-block;
}The menu now shows bullets and an indent, because ul li matches it too. The menu author sees the bullets and adds list-style: none; margin-left: 0;. That works, but now the menu has two rules that exist only to cancel a rule defined elsewhere. If the article rule changes, the menu might break again, and nothing in the code links the two.
Compare this with a version where each rule is scoped by a class.
.article-list {
list-style: disc;
margin-left: 1.5rem;
}
.menu__list {
list-style: none;
margin: 0;
padding: 0;
}Each rule now applies only to elements that opt in. Nothing needs to cancel anything. This is the idea behind the naming and component techniques in later chapters.
What does not scale
Some habits work in small projects and fail in large ones.
| Habit | Why it fails at scale |
|---|---|
| Styling bare elements such as `ul li` or `div p` | Matches anything, including parts you did not intend |
| Deep descendant selectors | Couples CSS to the exact HTML structure |
| IDs in selectors | Very high specificity, hard to override |
| `!important` as a fix | Forces the next override to also use `!important` |
| One large file, edited by everyone | Merge conflicts and no clear ownership |
| Unnamed or inconsistent class names | Collisions and unclear purpose |
| Hard-coded values | Changes need a search across the codebase |
Element selectors are not forbidden. A reset or base layer that styles body or a is reasonable. The problem is using them for component styling, where the reach is hard to predict.
Goals for a maintainable codebase
The rest of the tutorial applies techniques that serve a small set of goals. These goals give you a way to judge any technique.
- Predictable. You can read a rule and know what it affects.
- Low and even specificity. Most selectors have similar weight, so source order or explicit layers decide ties, not selector tricks.
- Isolated. A component's styles do not leak out and others do not leak in.
- Consistent. Names, values and file locations follow rules that tools can check.
- Deletable. You can remove a component's CSS together with its markup and expect nothing else to break.
- Cheap to deliver. Users download only the CSS they need.
Roadmap
Each problem in this chapter maps to techniques covered later.
| Problem | Technique | Chapter topic |
|---|---|---|
| Name collisions | Naming conventions, BEM, scoping | Naming, BEM, scoping |
| Specificity wars | Single-class selectors, `@layer` | Cascade, `@layer` |
| Order-dependent results | Layered architecture, cascade layers | Architecture, `@layer` |
| Duplicated values | Design tokens | Custom properties |
| Unclear structure | File and folder organisation | Files and folders |
| Inconsistent code | Stylelint | Linting |
| Fear of deletion | Refactoring and dead CSS removal | Refactoring |
| Heavy downloads | Bundling and splitting | Delivery |
Diagnosing your own codebase
Before changing anything, measure. Two quick checks give a baseline you can compare against later.
Count !important declarations and ID selectors with a shell command:
grep -rEo "!important" src --include="*.css" | wc -l
grep -rEo "#[a-zA-Z_-]+[ ,{.:>+~[]" src --include="*.css" | wc -lThe second pattern is approximate. It also matches some hex colors that are followed by those characters, so treat the number as an upper bound. Later chapters replace it with Stylelint rules that report exact counts.
Then open your browser's developer tools, inspect a stubborn element, and look at the Styles panel. Crossed-out declarations are rules that lost the cascade. Many crossed-out rules on one element, from several files, show the cycle in action.
Exercise
A developer finds that .button { background: blue; } in button.css has no effect on one page. Another rule, .sidebar .button { background: grey; }, applies instead. Name the mechanism, and give one fix that does not use !important or an ID.
Show answer
The mechanism is specificity. .sidebar .button is 0,2,0 and .button is 0,1,0, so the grey rule wins even if button.css loads later. One fix is to remove the .sidebar .button background rule and give the sidebar button a modifier class such as .button--muted with the grey background, so that all button rules stay at 0,1,0 and source order decides ties. Another fix is to raise the intended rule to the same weight, but that adds to the arms race, so the modifier is preferable.
Exercise
Two stylesheets define .title with different font sizes. The page shows the larger size. List two different reasons this could be the case, and say how you would tell them apart.
Show answer
Either the larger rule has higher specificity (for example .report .title against .title), or the specificities are equal and the larger rule appears later in the cascade. In the browser's Styles panel, compare the selectors of the two declarations. If the selectors differ in weight, specificity decides. If they are identical in weight, source order decides, and you can confirm by checking the order of the stylesheets in the Network or Elements panel.
Exercise
Why can the same CSS render differently after a change to the bundler configuration, even though no CSS file changed?
Show answer
The bundler controls the order in which files are concatenated or injected. Where rules have equal specificity, the later one wins, so a changed order changes which declaration applies.