Sub topic 12
Refactoring and removing dead CSS safely
This chapter assumes you know the cascade and specificity, can read BEM class names, and have used npm and Node scripts. It also assumes you have seen Stylelint configured in a project. The goal is to delete and restructure CSS in a large codebase without breaking pages that nobody remembered to check.
Why dead CSS builds up
CSS has no compiler error for an unused rule. A selector that matches nothing costs the browser a little parsing time and costs the team a lot of reading time. Developers keep it because deleting it feels risky: the stylesheet is global, so any page might depend on the rule.
Dead CSS usually arrives through a few routes:
- A component is removed from the markup, but its stylesheet stays.
- A class is renamed in the HTML, and the old selector is left behind.
- A later rule overrides every declaration of an earlier rule, so the earlier rule never wins.
- A feature is shipped behind a flag, and the flag is retired.
- A selector is so specific that no element can match it any more.
Each route needs a different detection method, so treat "dead CSS" as several problems.
Kinds of dead CSS and how to find them
| Kind | Symptom | Detection |
|---|---|---|
| Unreferenced class | No file in the source mentions the class | Text search, a script, PurgeCSS |
| Unreached rule | The class exists in markup, but the rule never applies on any page or state | Browser coverage across many page states |
| Fully overridden rule | Every declaration is struck through in DevTools | Manual review, `no-duplicate-selectors` |
| Duplicate declaration | The same property appears twice in one block | Stylelint |
| Unused custom property | A token is defined but never read through `var()` | Text search for the token name |
The first two kinds are the dangerous ones to delete. Static tools can only prove that a name does not appear in your source. They cannot prove that a name is never built at runtime.
Step 1: Make the problem visible
Before you delete anything, measure. A baseline lets you show that a change helped and lets you notice if it did not.
- Record the size of each built stylesheet, raw and compressed.
- Count rules, selectors and
!importantdeclarations. - Run Stylelint and note the number of warnings.
The following script finds class names that are defined in a stylesheet but never appear as text in your source. It needs Node 18 or later.
// find-unused-classes.mjs
import { readFileSync, readdirSync, statSync } from "node:fs";
import { join, extname } from "node:path";
const [cssFile, srcDir] = process.argv.slice(2);
if (!cssFile || !srcDir) {
console.error("Usage: node find-unused-classes.mjs <file.css> <srcDir>");
process.exit(1);
}
function* walk(dir) {
for (const name of readdirSync(dir)) {
if (name === "node_modules") continue;
const path = join(dir, name);
if (statSync(path).isDirectory()) yield* walk(path);
else yield path;
}
}
const css = readFileSync(cssFile, "utf8").replace(/\/\*[\s\S]*?\*\//g, "");
// Collect class names from selectors only (the text before each "{").
const classes = new Set();
for (const [, prelude] of css.matchAll(/([^{}]+)\{/g)) {
for (const [, name] of prelude.matchAll(/\.(-?[_a-zA-Z][\w-]*)/g)) {
classes.add(name);
}
}
const extensions = new Set([".html", ".js", ".jsx", ".ts", ".tsx", ".vue", ".svelte"]);
let source = "";
for (const file of walk(srcDir)) {
if (extensions.has(extname(file))) source += readFileSync(file, "utf8") + "\n";
}
const unused = [...classes].filter((name) => !source.includes(name)).sort();
console.log(`${unused.length} of ${classes.size} classes not found in source:`);
for (const name of unused) console.log(` .${name}`);Run it with node find-unused-classes.mjs dist/main.css src. The check is a plain substring match, so it errs toward keeping a class. A class named card is "found" if the word card appears anywhere. That is deliberate: a false "used" costs a few bytes, while a false "unused" breaks a page.
The output is a list of candidates. It is not a list of things to delete.
Step 2: Account for dynamic class names
The main failure of every static tool is a class name assembled at runtime:
const size = props.large ? "large" : "small";
element.className = `button button--${size}`;The text button--large appears nowhere in this file. A script, or a purge tool, will report .button--large as unused and you will remove a style that users see. The same happens with classes added by a third-party widget, classes stored in a CMS, and classes toggled from data attributes or a server template.
You have three defences:
- Write class names out in full in the source, for example with a lookup object:
{ large: "button--large", small: "button--small" }. Then text search works. - Add the pattern to a safelist in your purge tool.
- Treat any prefix that is built dynamically (
button--,is-,has-) as protected until proven otherwise.
PurgeCSS supports the last two. A minimal configuration looks like this:
// purgecss.config.js
module.exports = {
content: ["src/**/*.html", "src/**/*.js", "src/**/*.jsx"],
css: ["dist/main.css"],
safelist: {
standard: ["is-open", "is-active"],
greedy: [/^button--/, /^toast-/],
},
};Run npx purgecss --config purgecss.config.js --output tmp/ and compare tmp/main.css with the original. Write to a separate folder first and diff the result. Do not overwrite the source stylesheet.
Step 3: Confirm with the browser
The Coverage panel in Chrome DevTools records which bytes of each stylesheet were applied while you used the page. Start recording, load the page, then open menus, dialogs, error states and every breakpoint you support. Red regions are rules that did not apply during your session.
Coverage proves only that a rule was unused in that session. A rule for a validation error message will look dead until you submit a bad form. Use coverage to rank candidates, then confirm each one against the source.
For fully overridden rules, inspect an element in the Styles panel. A declaration that is struck through on every element that matches is a candidate for deletion. Check at least one of each variant, since a rule overridden on one page may win on another.
Step 4: Delete in small, reversible steps
Practical habits that make this safe:
- Delete one component or one folder per commit, so a revert undoes only that change.
- Run visual regression tests or screenshot comparisons on key pages before and after.
- Deprecate before you delete. Add a comment such as
/* deprecated: remove after 2026-03 */and a Stylelint or grep check that fails if new markup uses the class. - Ship removals separately from feature work, so a bug has one obvious suspect.
Refactoring overridden and over-specific CSS
Deleting is half the job. The other half is making the remaining CSS cheaper to change. Typical legacy code looks like this:
#main .sidebar .card .title {
font-size: 1.5rem;
}
.page-home .card .title {
font-size: 1.25rem !important;
}The !important exists because the first rule is too specific to beat any other way. Replace the chain with a single-class selector and a modifier:
.card__title {
font-size: 1.5rem;
}
.card--compact .card__title {
font-size: 1.25rem;
}Do this migration in three stages, so that no stage leaves the page broken:
- Add the new class names to the markup next to the old ones.
- Move the declarations to the new selectors. Confirm in DevTools that the new rules are the ones that win.
- Remove the old class names from the markup, then delete the old rules.
Raising or lowering specificity changes which rule wins. Compare the computed styles of representative elements before and after, not only the source diff. If your project uses @layer, put legacy CSS in a low-priority layer such as legacy. New components in later layers then win without !important, and you can shrink the legacy layer over time.
Keep it clean afterwards
Add Stylelint rules that catch the cheap mistakes automatically:
{
"extends": "stylelint-config-standard",
"rules": {
"no-duplicate-selectors": true,
"declaration-block-no-duplicate-properties": true,
"no-descending-specificity": true,
"declaration-no-important": true
}
}The standard preset typically enables several of these already. Listing them states the intent and survives a preset change. no-descending-specificity flags a selector that comes after a more specific selector for the same element, which is a common sign of an override fight.
Common mistakes
- Trusting a single page's coverage report. Rules for other pages and states look unused.
- Purging the output of a build that already includes third-party CSS, then losing library styles.
- Deleting a rule that a JavaScript library adds classes for at runtime.
- Removing a custom property that is only read from JavaScript through
getComputedStyle. - Combining a rename, a deletion and a visual redesign in one pull request.
Exercise
Your script reports .badge--warning as unused, but the code contains className={badge badge--${level}}. Explain what is wrong and give two ways to avoid a wrongful deletion.
Show answer
The full class name never appears as text, because it is built at runtime from level, so a static search cannot see it. Two fixes: write the names out in full, for example a lookup object mapping each level to "badge--warning", so text search finds them; or safelist the prefix, such as /^badge--/ in PurgeCSS, so the rules are never removed automatically.
Exercise
A rule shows as red in the DevTools Coverage panel after you load a page. List two reasons it may still be needed, and name the next step before deleting it.
Show answer
It may apply only to a state you did not trigger, such as a form error, an open dialog or a hover or focus style. It may also belong to another page or breakpoint that shares the stylesheet. The next step is to search the source for the class, and exercise the relevant states and breakpoints. Delete it only in a small, revertible commit.