CSS-2Recommended
Sort styles into five layers
Put every style you write in one of five layers, in the order tokens, base, layout, components and utilities. Each layer has its own folder, and a file belongs to exactly one layer. Third-party CSS sits in one vendor layer before them.
How to do it
Tokens hold custom properties only, as Take every style value from design tokens describes. Base styles bare elements such as body, a and table, with no classes. Layout places regions of the page. Components style one module each. Utilities are the few single-purpose classes on the written list from Give every module its own class names. A later layer may use what an earlier layer defines, never the other way round. Packages you install never go in these five folders. They load into the vendor layer, as Import third-party CSS into its own layer describes.
Examples
CSS example
/* tokens/index.css: custom properties only */
:root { --surface: Canvas; --text: CanvasText; }
/* base/elements.css: bare elements, no classes */
a { color: var(--text); }
/* components/order-card.css: one module */
.order-card { background: var(--surface); }
JavaScript example
// A build check: base files contain no class selectors
import { readFileSync, readdirSync } from 'node:fs';
const failures = readdirSync('styles/base')
.filter(file => /\.[a-z][\w-]*\s*[{,:]/.test(readFileSync(`styles/base/${file}`, 'utf8')));
failures.forEach(file => console.log(`FAIL styles/base/${file} selects a class`));
process.exit(failures.length ? 1 : 0);
Python example
# The same check in Python
import pathlib, re, sys
failures = [p for p in pathlib.Path("styles/base").glob("*.css")
if re.search(r"\.[a-z][\w-]*\s*[{,:]", p.read_text())]
for p in failures:
print(f"FAIL {p} selects a class")
sys.exit(1 if failures else 0)
How to check
Every CSS file you write sits in one of the five folders. Files in tokens/ declare only custom properties. Files in base/ contain no class selectors. Files in utilities/ define only classes on the written list.
Sources
Related rules
- CSS-1 Load every stylesheet from one entry file in HTML and CSS
- APP-1 Take every style value from design tokens in Web app interface
- CSS-10 Fence each component's styles in in HTML and CSS
- CSS-12 Import third-party CSS into its own layer in HTML and CSS
- CSS-6 Declare the layer order once in HTML and CSS
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/html-css/structure-and-files/five-style-layers">Agent Wranglers HTML and CSS playbook</a>. In code you write, add a comment next to it with the same link.