Pattern Libraries, a CSS-First Workflow and Refactoring Safely
Keeping a large stylesheet healthy: documenting modules in a pattern library, building CSS before pages, finding unused CSS with coverage, screenshot tests, linting, deprecating and versioning modules, and migrating legacy CSS with a low layer.
kvi5hnuCode Sprout team member9 min readOn this page
Writing modular CSS (article 116) and organizing it in layers (article 117) keeps a stylesheet understandable. Keeping it that way, while a team adds features for years, needs a few habits around the CSS: a place where every module is documented, a workflow that reuses modules before writing new ones, and tools that make changes and deletions safe.
Pattern libraries

A pattern library is an inventory of every module in the stylesheet, kept as a separate set of pages next to the site: not part of the product, but a tool for the people building it. Each entry usually shows:
- the module rendered, with every variant and state: hover, focus, disabled, error, empty, long text;
- the markup to copy, including required attributes like
aria-expanded; - usage notes: when to use it, what not to do, accessibility requirements;
- metadata: the class name, its layer, which tokens it uses, and a status such as stable, experimental or deprecated.
It doesn't need special software. A folder of plain HTML pages that load the real stylesheet works. Tools like Storybook, Fractal and Pattern Lab add navigation, controls for variants and automated tests, and they're common when the modules are also framework components. Design tokens (article 118) usually get their own pages too, showing every color, spacing step and type size.
Showing states side by side, as above, needs a way to display :hover without a pointer. Pattern libraries often add a documentation-only class, such as .is-hover, or use a tool option that forces the state.
A CSS-first workflow
Once a pattern library exists, building a new page changes. Instead of writing HTML and then styling it, you assemble it from modules that already exist, and the further a project goes, the less new CSS each page needs.
When a page does need something new, build the module in the pattern library first, then use it in the page:
- You design it in isolation, which makes you think about where else it might be used, so it ends up more general.
- You test every variant and state on one page, instead of hunting for them across the site.
- Work can be split: someone strong in CSS builds the module, and others use it by copying the documented markup.
- The documentation stays current, because it's where the CSS is developed and tested.
The question changes from "how do I write HTML that's easy to style?" to "which modules does this page need?" The modules define the HTML structure they expect, and the library documents it.
Finding unused CSS
Stylesheets grow mostly because deleting is scary: nobody knows whether an old rule is still used. Several tools help.
Coverage. Chrome DevTools' Coverage panel records which CSS rules matched anything while you use a page:

This report was measured on a page with only a card and a button: 64% of the stylesheet didn't match anything there. Notice .button:hover: it's needed, but nothing was hovered during the recording. Coverage shows what one session used, not what's safe to delete, so record every page and interaction, or use it to find candidates and then confirm.
Search. Search the codebase for each candidate class name. That only works if class names appear in full in the source: build "button--" + variant dynamically and a search for button--danger finds nothing. Keep complete class names in templates, or keep a list of the generated ones.
Linters. Stylelint can enforce the conventions that keep a stylesheet maintainable, for example:
| Rule | Prevents |
|---|---|
selector-max-id: 0 | IDs in selectors |
selector-max-specificity | specificity creeping up |
selector-class-pattern | class names that break the naming convention, such as BEM |
declaration-no-important | !important outside approved places |
selector-max-compound-selectors | long descendant chains like .a .b .c .d |
Screenshot tests
A CSS change can break pages you never looked at. Visual regression tests take screenshots of pages or components, compare them with approved screenshots pixel by pixel, and fail when something changed:

Here, one innocent-looking change to paragraph line height moved the second line of text, the button and the card's bottom edge, and the comparison flagged 2.5% of the pixels. A person then decides whether that's intended, and if it is, the new screenshot becomes the reference.
- Test runners such as Playwright (
expect(page).toHaveScreenshot()) and tools like BackstopJS do this. Pattern library pages make ideal test pages, since they show every module in every state. - Fix sources of noise: use fixed fonts and viewport sizes, disable animations, and hide dynamic content like dates. A small threshold avoids failures from anti-aliasing differences.
Changing modules without breaking pages
Some changes to a module are incompatible with the HTML already using it, like a renamed element class or new required markup. You can update every page at once, but on a large site it's often safer to:
- Create a new module, or a new version of it, for the new design.
- Mark the old one deprecated in the pattern library, as with the crossed-out panel above, and move pages over gradually.
- Delete it once nothing uses it.
If the CSS is shared by several applications, version it with semantic versioning, major.minor.patch:
| Change | Version bump | Example |
|---|---|---|
| Bug fix, no markup change | patch | 4.2.0 → 4.2.1 |
| New module or variant, or a module newly deprecated | minor | 4.2.1 → 4.3.0 |
| Deprecated modules removed, or a redesign | major | 4.3.0 → 5.0.0 |
Each application loads a specific version, from a package manager or a versioned URL like /css/4.3.0/styles.css, and upgrades when its team is ready. The applications decide when to take breaking changes; the CSS can move ahead without breaking them.
Tokens can be deprecated the same way: keep the old name as an alias, --color-primary: var(--color-accent);, until nothing uses it.
Migrating legacy CSS with a layer
An old stylesheet full of IDs and long selectors usually beats any new, low-specificity module. Instead of fighting it with even stronger selectors, import the whole thing into the lowest layer:
@layer legacy, reset, theme, base, layout, components, utilities;
@import url("old-site.css") layer(legacy);
Now every new layer beats the old CSS regardless of its specificity, and pages can move to new modules one at a time.
One thing to watch, visible in the playground below: layers only decide between declarations of the same property. With the old CSS in the legacy layer, the widget gets the new background, heading and button, but keeps the old gray border, because the new component never sets border. Either set every property the old CSS touched (here border: 0), or start the new rule with all: revert, which rolls every property back to the browser's defaults before the module's own declarations apply. Tested in Chrome, .widget { all: revert; padding: 13px; } in the components layer removed the legacy border and kept the new padding. Don't use revert-layer for this: it does the opposite, falling back to the legacy layer's value. Within a component, revert-layer (article 20) can switch a property back to what the legacy layer says, where needed. As modules replace old rules, coverage and search show when parts of old-site.css can go.
/* the new, layered stylesheet */
@layer legacy, components;
@layer components {
.widget { padding: 0.8rem; border-radius: 10px; background: #f4efe6; }
.widget h4 { margin: 0 0 0.5rem; font: 700 1rem system-ui, sans-serif; color: #2a2118; }
.button { padding: 0.45em 0.95em; border: 0; border-radius: 7px; background: #8a3b12; color: white; font: 600 0.9rem system-ui, sans-serif; }
}
body { font: 0.85rem system-ui, sans-serif; margin: 1rem; }
.toggle { display: flex; gap: 0.4rem; align-items: center; margin-block-end: 0.8rem; }
.note { color: #555; }
Unchecked, the old rules are unlayered, and unlayered styles beat all layers, so the widget looks dated. Checked, the same rules sit in the lowest layer and the new components take over, without changing a single selector.
What's current
- Chrome DevTools has a Coverage panel for CSS and JavaScript; Firefox and Safari don't have an equivalent for CSS yet.
- Screenshot comparison is built into common test runners such as Playwright.
- Cascade layers make legacy migration far easier than the specificity wars they replace.
Common questions
Is a pattern library worth it for a small site? A single page that shows every module with its variants is cheap and pays off quickly. Full tooling can wait.
Can I delete everything Coverage marks unused? No. It only knows what happened during one recording. Use it to find candidates, then search the code and check other pages and states.
Why do my screenshot tests fail randomly? Something differs between runs: fonts loading late, animations, dates, or different machines. Fix fonts and viewport, disable motion, and run tests in the same environment.
How do I override a legacy stylesheet that uses IDs everywhere? Import it into the lowest layer. Any layered or unlayered new rule then beats it.
Summary
- A pattern library documents every module with its variants, states, markup and usage.
- Build new modules in the library first, then assemble pages from them.
- Coverage, full class names in source, and linters make deleting and changing CSS safer.
- Screenshot tests catch unintended visual changes.
- Deprecate and version modules instead of breaking existing pages.
- Put legacy CSS in the lowest layer to migrate gradually.
Practice questions
Coverage marks .dropdown.is-open .dropdown__drawer unused on a page that has a dropdown. Should you delete it?
Answer
No. The rule applies only after the dropdown is opened. Coverage records what matched during the recording, so either open the dropdown while recording or confirm by searching the code.
Why is this a problem for maintaining CSS?
el.className = `alert alert--${level}`;
Answer
Searching the code for alert--warning finds nothing, so it's hard to tell whether that modifier is used. Write the full class names, for example in a lookup table: { warning: 'alert alert--warning', error: 'alert alert--error' }.
Your team removes the deprecated .panel module from a shared stylesheet at version 3.8.2. What's the next version number?
Answer
4.0.0. Removing a module breaks HTML that still uses it, so it's a major change.
Write the start of a stylesheet that lets new components override an old legacy.css full of ID selectors.
Answer
@layer legacy, base, components, utilities;
@import url("legacy.css") layer(legacy);
Previous: Design Tokens and Theming With Custom Properties
Next: Preprocessors and Tooling: Sass, PostCSS, Lightning CSS and What Native CSS Replaced

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.