CSS-3Recommended
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, so a conflict is never settled by which file loads last.
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. When two rules of the same layer and specificity match one element, the later file wins without any warning. Reorder an import or split a bundle, and the look changes on some pages only. A deliberate override goes in a later layer or a variant.
Examples
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. A second script lists every selector defined in two or more stylesheets of the same layer, and the list is empty.
Sources
Related rules
- APP-4 Change components through variants in Web app interface
- CSS-9 Keep !important inside the utilities layer in HTML and CSS
- CSS-25 Name custom elements with the project prefix 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/component-stylesheet">Agent Wranglers HTML and CSS playbook</a>. In code you write, add a comment next to it with the same link.