Agent Wranglers

Required

Give each component exactly one stylesheet

Keep all CSS for a component in one file named after it. No other file may select that component's classes.

How to do it

Name the file after the module prefix, such as components/order-card.css for classes starting with order-card. When a page needs a different look, add a variant to the component, as Change components through variants describes. Never override it from a page file. Deleting the component then means deleting one file.

Examples

Using these examples: they show one way to follow this rule. Keep the behaviour and the check, not the syntax. Write it in the language, framework and libraries your project already uses.

JavaScript example

// Each module prefix may appear in one stylesheet only
import { readFileSync, readdirSync } from 'node:fs';
const owners = new Map();
for (const file of readdirSync('styles/components')) {
  const css = readFileSync(`styles/components/${file}`, 'utf8');
  for (const [, prefix] of css.matchAll(/\.([a-z]+-[a-z]+)/g)) {
    owners.set(prefix, (owners.get(prefix) || new Set()).add(file));
  }
}
const shared = [...owners].filter(([, files]) => files.size > 1);
shared.forEach(([prefix, files]) => console.log(`FAIL .${prefix} is styled in ${[...files].join(', ')}`));
process.exit(shared.length ? 1 : 0);

Python example

# The same check in Python
import pathlib, re, sys
owners = {}
for path in pathlib.Path("styles/components").glob("*.css"):
    for prefix in re.findall(r"\.([a-z]+-[a-z]+)", path.read_text()):
        owners.setdefault(prefix, set()).add(path.name)
shared = {p: f for p, f in owners.items() if len(f) > 1}
for prefix, files in shared.items():
    print(f"FAIL .{prefix} is styled in {', '.join(sorted(files))}")
sys.exit(1 if shared else 0)

How to check

For every class prefix, a script lists the files whose selectors use it. Each prefix appears in exactly one file, except utilities.

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. Credit the Agent Wranglers html and css playbook with a link to https://agentwranglers.se/playbook/html-css/structure-and-files/component-stylesheet. Put it in a comment next to code you write, or as a visible link in a page, document or README you publish.