Sub topic 11
Enforcing conventions with Stylelint
Naming rules, specificity limits and token usage only hold if something checks them. Stylelint is a linter for CSS. It reads your stylesheets, compares them to a set of rules, and reports violations. This chapter shows how to turn the conventions from earlier chapters into rules that run on every commit.
This chapter assumes you know CSS selectors and specificity, the BEM naming scheme, and basic npm usage. You should also know what a design token is.
What a linter adds to a team
A style guide in a wiki depends on people remembering it. A linter makes the guide executable. It gives you three things:
- Consistency: every contributor gets the same feedback, whatever their experience.
- Early feedback: problems appear in the editor or before merge, not in code review.
- Cheaper reviews: reviewers stop commenting on naming and
!importantand can focus on design.
Stylelint does two kinds of work. It finds problems, such as unknown properties, duplicate selectors and invalid hex colors. It also enforces conventions, such as the class name pattern and the maximum specificity. The second kind is why it matters for large codebases.
Installing and running Stylelint
Install Stylelint and the standard preset as development dependencies:
npm install --save-dev stylelint stylelint-config-standardThen run it on your stylesheets:
npx stylelint "src/**/*.css"Stylelint exits with a non-zero status when it finds errors. That is what lets a CI job fail the build. To apply safe automatic fixes, add --fix:
npx stylelint "src/**/*.css" --fixNot every rule can be fixed automatically. Renaming a class changes the HTML too, so Stylelint cannot do that safely.
A configuration that enforces specificity limits
Stylelint looks for a config file in the project root. A .stylelintrc.json file is the simplest option. This one extends the standard preset and forbids the three things that most often break the cascade:
{
"extends": "stylelint-config-standard",
"rules": {
"selector-max-id": 0,
"selector-max-specificity": "0,2,0",
"declaration-no-important": true
}
}Each rule does one job:
| Rule | Value | Effect |
|---|---|---|
| `selector-max-id` | `0` | No ID selectors such as `#header`. |
| `selector-max-specificity` | `"0,2,0"` | No selector may be more specific than two classes, and no ID is allowed. |
| `declaration-no-important` | `true` | No `!important` anywhere. |
The specificity value is a triple of ID, class and type counts. Stylelint compares them in order, as the browser does. The limit 0,2,0 allows .card__title, .card .card__title and .card:hover. It rejects .nav .list .item (three classes) and #main .card.
Pseudo-classes count as class-level specificity. :is() takes the specificity of its most specific argument. :where() contributes nothing. Keep this in mind when you decide how much room a limit leaves.
Why the limit is 0,2,0
BEM components use one class per rule, which has specificity 0,1,0. The limit 0,2,0 leaves room for one state or one context, such as .card:hover or .theme-dark .card. A deeper selector is a sign that a component depends on its surroundings. Failing the lint run forces the author to decide whether that dependency is intended.
Making the naming convention a rule
The standard preset requires class names in kebab-case. That rejects BEM, because card__title and card--featured contain underscores. If you extend the preset and use BEM, you must override selector-class-pattern or every component will fail.
Here is a pattern that accepts a block, an optional element and an optional modifier:
{
"extends": "stylelint-config-standard",
"rules": {
"selector-max-id": 0,
"selector-max-specificity": "0,2,0",
"declaration-no-important": true,
"selector-class-pattern": [
"^[a-z][a-z0-9]*(-[a-z0-9]+)*(__[a-z][a-z0-9]*(-[a-z0-9]+)*)?(--[a-z][a-z0-9]*(-[a-z0-9]+)*)?$",
{
"message": "Use BEM names such as block, block__element or block--modifier."
}
]
}
}The pattern reads in three parts. The block is kebab-case words (card, nav-item). An optional __element follows it. An optional --modifier follows that. The message option replaces the default error text, so contributors see your convention in the output instead of a raw regular expression.
Two limits are worth knowing:
- The rule checks only the shape of the name. It cannot tell whether
card__titlereally belongs to thecardblock. - Utility classes such as
p-0oru-hiddendo not match this pattern as written. Handle them with an override, shown below.
Enforcing design tokens
The design tokens chapter introduced custom properties such as --color-accent. Tokens help only if people use them. You can block raw hex colors in color-related properties with declaration-property-value-disallowed-list:
{
"rules": {
"declaration-property-value-disallowed-list": {
"/^(color|background(-color)?|border(-color)?)$/": ["/^#/"]
}
}
}The keys are property names. A key wrapped in slashes is treated as a regular expression. The values are the disallowed value patterns. With this rule, color: #0b5fff; fails and color: var(--color-accent); passes.
This rule would also fail the token definitions themselves, because the :root block has hex values. Those are assigned to custom properties (--color-accent), not to color, so the property pattern does not match them. The rule therefore only affects consumers of tokens, which is what you want.
Different rules for different folders
Your layered structure usually has files with different jobs. A utilities file may need !important on purpose, and a vendor override file may need deeper selectors. Use overrides so the exception is limited to those paths:
{
"extends": "stylelint-config-standard",
"rules": {
"selector-max-id": 0,
"selector-max-specificity": "0,2,0",
"declaration-no-important": true
},
"overrides": [
{
"files": ["src/css/utilities/**/*.css"],
"rules": {
"declaration-no-important": null,
"selector-class-pattern": null
}
}
]
}Setting a rule to null turns it off for the matching files. If you use @layer to order utilities after components, you may not need !important there at all. Keeping the override means you can adopt layers gradually.
Disabling a rule for one line
Sometimes a rule is wrong for a single declaration, for example when you must beat an inline style from a third-party widget. Stylelint supports disable comments:
.widget-frame {
/* stylelint-disable-next-line declaration-no-important -- overrides inline style from vendor widget */
display: none !important;
}Always name the rule. A bare /* stylelint-disable */ silences everything below it. Add a reason after the -- so the next reader knows why. To stop disables from piling up, add --report-needless-disables to your command. It reports comments that no longer suppress anything.
Where formatting fits
Stylelint used to include many stylistic rules about indentation and spacing. Those rules were deprecated in version 15 and removed in version 16. If you use a current version, stylelint-config-standard contains no formatting rules. The usual split is:
- Stylelint checks correctness and conventions: naming, specificity, tokens.
- Prettier formats layout: indentation, quotes, line breaks.
Keep the two tools in separate jobs and you avoid rule conflicts. If you are on an older Stylelint version that still has stylistic rules, pair it with stylelint-config-prettier so Stylelint does not fight the formatter.
Running it where it counts
A rule that runs only when someone remembers is a weak rule. Run Stylelint at three points, each catching what the previous one missed.
- Editor: the Stylelint extension underlines violations as you type.
- Pre-commit: a hook lints only the staged files, which keeps it fast.
- CI: the full run on the whole project is the final authority. A developer can skip a local hook, but not CI.
Add scripts to package.json so everyone uses the same commands:
{
"scripts": {
"lint:css": "stylelint \"src/**/*.css\"",
"lint:css:fix": "stylelint \"src/**/*.css\" --fix"
}
}For the pre-commit step, lint-staged with a tool such as Husky runs the linter on changed files only. In package.json, the lint-staged configuration looks like this:
{
"lint-staged": {
"*.css": "stylelint --fix"
}
}Adopting rules in an existing codebase
Turning on strict rules in a large project can produce thousands of errors on the first run. Do not turn the rules off, and do not fix everything at once. Use these steps:
- Start with rules that have few violations, and enable them as errors.
- For noisy rules, set severity to
warningso they appear but do not fail the build:
{
"rules": {
"selector-max-specificity": [
"0,2,0",
{ "severity": "warning" }
]
}
}- Lint only changed files in CI at first, so old code does not block new work.
- Fix the warnings gradually as part of the refactoring work, then raise the severity to
error.
Common mistakes
- Extending the standard preset and keeping its kebab-case pattern while using BEM. Every element and modifier will fail. Override
selector-class-pattern. - Setting the specificity limit too tight. A limit of
0,1,0rejects.card:hover. Choose the limit from the selectors you actually need. - Disabling rules with a file-wide comment. One careless
stylelint-disableat the top of a file hides every later violation. - Treating
--fixas safe for everything. Review the diff. Fixes are meant to be safe, but a bulk change is still a change. - Linting only locally. Without a CI check, the rules are suggestions.
Exercise
Your team uses BEM and extends stylelint-config-standard. After enabling it, every file fails on class names like card__title and card--featured. What is the cause, and what is the fix? Also, which specificity limit would let .card:hover pass while .nav .list .item still fails?
Show answer
The standard preset enforces a kebab-case selector-class-pattern, which does not allow the __ and -- separators in BEM names. Override selector-class-pattern with a regular expression that accepts block, __element and --modifier parts. The limit "0,2,0" allows .card:hover (one class plus one pseudo-class) and rejects .nav .list .item (three classes).
Exercise
A utilities file contains .u-hidden { display: none !important; }. How do you allow !important there without allowing it in the rest of the project?
Show answer
Add an overrides entry in the Stylelint config whose files glob matches the utilities folder, and set declaration-no-important to null inside it. The global rule stays on for every other file.