Sub topic 14
Documenting Patterns and Style Guides
This chapter assumes you can already write BEM components, define design tokens as custom properties, and run a Node script from the command line. Earlier chapters gave you conventions and tools. This chapter covers how to write them down so the next developer can follow them without asking you.
Why documentation matters in CSS
A convention that lives only in people's heads degrades as the team changes. New developers copy the nearest example, and the nearest example may be a bad one. Documentation gives them a better one to copy.
Good CSS documentation answers four questions:
- What exists? Which tokens, components and utilities are available.
- How do I use it? The markup, the modifiers and the states.
- What are the rules? Naming, layer order, and specificity limits.
- Why was it done this way? The decisions behind the rules, so people stop relitigating them.
Each question suits a different format, and mixing them in one document makes all of them harder to read.
| Question | Best format | Where it lives |
|---|---|---|
| What tokens exist? | Generated table | Built from the token file |
| How do I use a component? | Rendered example plus markup | Style guide next to the CSS |
| What are the rules? | Short written guide | `CONTRIBUTING.md` or a docs page |
| Why this approach? | Decision record | A `docs/decisions/` folder |
Documenting tokens
Tokens are the easiest thing to document because they are already structured data. A table that someone writes by hand will drift from the real values within weeks. Generate it from the source instead.
Start with a token file that has comments describing intent, not just values.
/* tokens.css */
:root {
/* Body text on the default background. */
--color-text: #1a1a1a;
/* Interactive elements: links, buttons, focus rings. */
--color-accent: #0b5fff;
/* Smallest gap between related items. */
--space-2: 0.5rem;
/* Default gap inside components. */
--space-4: 1rem;
}The following Node script reads that file and prints a Markdown table. Save it as tokens-table.mjs so Node treats it as an ES module.
import { readFileSync } from "node:fs";
const source = readFileSync("tokens.css", "utf8");
const css = source.replace(/\/\*[\s\S]*?\*\//g, "");
const rows = [];
for (const match of css.matchAll(/--([\w-]+)\s*:\s*([^;]+);/g)) {
rows.push(`| \`--${match[1]}\` | \`${match[2].trim()}\` |`);
}
console.log("| Token | Value |\n| --- | --- |\n" + rows.join("\n"));The script strips comments before matching. Without that step, a comment such as /* use --color-text: for body */ would produce a false row.
This version drops the intent comments from the output. If you want them in the table, switch to a documentation tool that understands comment annotations, or write the descriptions as a structured block above each token. Either way, the rule is the same: the token file is the single source, and the documentation is built from it.
Documenting components
A component entry needs five things: a one-line purpose, the markup, the modifiers, the states, and any restrictions. For BEM components, the class names already carry much of this structure, so the documentation can stay short.
You can keep documentation next to the CSS in a structured comment.
/**
* Card
*
* A bordered container for a short summary with a title and body.
*
* Elements: .card__title, .card__body
* Modifiers: .card--featured Gold border for highlighted items.
*
* Do not nest a .card inside another .card.
*/
.card {
padding: 1rem;
border: 1px solid #ddd;
}
.card__title {
font-size: 1.25rem;
}
.card--featured {
border-color: gold;
}The matching markup example shows the block class combined with its modifier.
<article class="card card--featured">
<h2 class="card__title">Release notes</h2>
<p class="card__body">What changed this week.</p>
</article>Comments next to the code have one strong advantage. A developer who edits the rule sees the documentation in the same diff. Their weakness is that nobody sees a rendered result. That is the gap a living style guide fills.
Living style guides
A living style guide is a page, built from your real components and real CSS, that shows each component in each state. "Living" means the page is generated from the code, so it cannot describe a component that no longer exists.
A static style guide is a separate document, such as a PDF or a wiki page. It looks fine on the day it is written and is wrong within a few releases.
Common tools for a living guide:
| Tool | Approach | Good fit |
|---|---|---|
| Storybook | Each component has "stories" written as code, rendered in isolation | Component-based front ends and design systems |
| Fractal | Components are template files with config, rendered into a browsable library | Server-rendered templates |
| Pattern Lab | Atomic design hierarchy built from templates | Teams following atomic design |
| A hand-built docs page | Plain HTML that links the production stylesheet | Small projects with a few components |
The last row is a legitimate option. A single HTML page that loads your real stylesheet and shows every component costs almost nothing and cannot drift, because it uses the same CSS.
Here is a Storybook story for the card, using the @storybook/html renderer. It assumes the card styles live in card.css in the same folder.
import "./card.css";
export default {
title: "Components/Card",
tags: ["autodocs"],
argTypes: {
featured: { control: "boolean" },
},
};
export const Default = {
args: { featured: false },
render: ({ featured }) => `
<article class="card${featured ? " card--featured" : ""}">
<h2 class="card__title">Release notes</h2>
<p class="card__body">What changed this week.</p>
</article>`,
};The featured control gives readers a checkbox that toggles the modifier. They can see what the modifier does without reading the CSS.
How the pieces fit together
The best setup has one source of truth and several outputs. Developers edit CSS. A build step produces the token table and the style guide. CI publishes both.
Documenting rules and decisions
Rules need a short written guide. Keep it to what a contributor must know before opening a pull request. A useful structure is:
- Naming: the BEM pattern, with one correct example and one wrong one.
- Specificity: the maximum your Stylelint config allows, and the reason for it.
- Layer order: the
@layerdeclaration, copied verbatim. - Tokens: never hard-code colors or spacing that a token covers.
- Where files go: the folder structure and what belongs in each folder.
Copying the real @layer line into the guide helps, because the order is easy to get wrong from memory.
@layer reset, base, components, utilities;Where possible, point to the Stylelint configuration as the authority for the rules it enforces, rather than restating them in prose. The following configuration is the rule set, and the guide only needs to explain it.
{
"extends": "stylelint-config-standard",
"rules": {
"selector-max-id": 0,
"selector-max-specificity": "0,2,0",
"declaration-no-important": true
}
}Decisions deserve their own short records, often called architecture decision records. Each one is a page with a title, the situation, the decision, and the consequences. For example, a record titled "Use BEM instead of CSS Modules" would state that the site renders on the server with templates, that CSS Modules need a bundler step the team does not run, and that the cost is longer class names. Six months later, someone proposing CSS Modules can read the record and find out whether those conditions have changed.
Keeping documentation accurate
Documentation fails when updating it is optional. These practices make accuracy the default:
- Generate what you can. Token tables, component lists and class inventories should come from the code.
- Render real CSS. A style guide that loads a copy of the stylesheet will diverge from production. Link the same built file.
- Build the guide in CI. If a component's story throws an error, the build fails and the problem is visible.
- Review docs in the same pull request. A rule such as "a new component needs an entry in the guide" is easy to enforce in review.
- Delete stale pages. A wrong page is worse than a missing one, because readers trust it.
Watch for these common errors:
- Documenting every property. Describe intent and usage. The CSS already shows the values.
- A guide that shows only the default state. Show hover, focus, disabled and error states, because those are where components break.
- Style guide styles leaking into the examples. The guide's own page CSS can override your components. Load the guide's chrome and the component styles in separate layers, or render examples in an isolated frame.
- Writing for the author. Test the guide on someone new. If they cannot build a card from it without help, it needs more examples and fewer descriptions.
Summary of the approach
Keep tokens documented by generation, components documented by rendered examples, rules documented by a short guide that points at the lint configuration, and decisions documented by dated records. All of these should live in the repository and build in CI.
Exercise
A teammate keeps a hand-written table of design tokens in the team wiki. Two tokens in the table no longer exist, and three new ones are missing. Describe how you would fix the process, not just the table.
Show answer
Treat the token file as the single source and generate the table from it, for example with a script that reads the custom properties from tokens.css and outputs Markdown. Run that script in CI and publish the result to the docs site, so the table updates whenever the tokens change. Remove the hand-written wiki table or replace it with a link to the generated one, so there is no second copy to drift.
Exercise
Your living style guide shows a card with a gold border, but production cards on the site have a gray border. Give two likely causes.
Show answer
The guide may load a copy or older build of the stylesheet instead of the same built file production uses. Or the guide page's own styles may override the component, for example because they sit in a later or higher-priority layer, or use higher specificity. Fix both by linking the production CSS and keeping the guide's chrome styles in a lower-priority layer or isolating the examples in a frame.