CSS-5Recommended
Write styles only in stylesheets
Keep every style declaration in a stylesheet. Templates have no style attributes or <style> elements. Scripts set no element.style property except a custom property through style.setProperty('--name', value). The one other exception is a <style> element the build writes from the bundled stylesheet.
How to do it
When a script must pass a value to CSS, set a custom property with style.setProperty('--progress', value) or a state attribute. A strict CSP does not block this, because it changes the style through the object model, not through markup. The stylesheet decides what the value does. This keeps every style in one searchable place and lets a strict Content Security Policy block inline styles. If the build inlines first-paint CSS, as Put the styles in the page says, list that element's SHA-256 hash in style-src instead of 'unsafe-inline'. The page-level gate is in Fail the build on broken rules.
Examples
JavaScript example
// Avoid: the script decides how it looks
bar.style.width = `${percent}%`;
// Do: the script passes a value, the stylesheet uses it
bar.style.setProperty('--progress', `${percent}%`);
Python example
# A source check: scripts may only set custom properties
import pathlib, re, sys
pattern = re.compile(r"\.style\.(?!setProperty\(\s*['\"]--)")
hits = [f"{p}:{n}" for p in pathlib.Path("src").rglob("*.js")
for n, line in enumerate(p.read_text().splitlines(), 1) if pattern.search(line)]
print("\n".join(f"FAIL {hit} sets a style directly" for hit in hits))
sys.exit(1 if hits else 0)
CSS example
.order-progress-bar { inline-size: var(--progress, 0%); }
How to check
The templates have 0 <style> elements. The built HTML has 0 style= attributes and at most one <style> element, whose hash the CSP style-src lists. The CSP has no 'unsafe-inline' in style-src. A search of the scripts finds 0 assignments to .style. other than setProperty('--…').
Sources
Related rules
- WEB-48 Put the styles in the page in Website
- ENG-3 Fail the build on broken rules in Engineering
- CSS-35 Keep untrusted data out of stylesheets in HTML and CSS
- CSS-34 Define every custom property a stylesheet reads in HTML and CSS
- CSS-38 Style web components through parts and custom properties 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/styles-only-in-stylesheets">Agent Wranglers HTML and CSS playbook</a>. In code you write, add a comment next to it with the same link.