Agent Wranglers

CSS-7Recommended

Cap selector specificity and keep ids out of selectors

Keep every selector at a specificity of 0,2,0 or lower. That is at most two classes, attributes or pseudo-classes, with no ids. Use ids only for links, labels and scripts.

How to do it

Low, even specificity lets layers and variants decide what wins, instead of selector weight. Wrap context in :where() when you need it, because :where() adds nothing to specificity. A selector that needs more weight to win is a sign the component has two owners. One id outweighs any number of classes, so a single #header rule beats every variant and forces !important to undo it. Keep ids for href="#...", for, aria-labelledby and aria-controls, named as Keep ids unique and stable says. Set the limit once in the style linter from Lint styles with one shared config.

Examples

CSS example

/* 0,1,0: the component root */
.booking-form { }

/* 0,2,0: a part in one state, the highest allowed */
.booking-form-field[aria-invalid="true"] { }

/* 0,1,0: context through :where() adds no weight */
:where(.booking-page) .booking-form { }

/* 1,2,1: fails the check */
#main .booking-form div.booking-form-field { }

HTML example

<!-- The id is for the label and the skip link, the class is for styling -->
<form class="booking-form" id="booking" aria-labelledby="booking-title">
  <h2 id="booking-title" class="booking-form-title">Book a table</h2>
</form>

JSON example

{
  "rules": {
    "selector-max-specificity": "0,2,0",
    "selector-max-id": 0
  }
}

How to check

The linter rules selector-max-specificity set to 0,2,0 and selector-max-id set to 0 report 0 problems on the whole project.

Sources

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/the-cascade/specificity-limit">Agent Wranglers HTML and CSS playbook</a>. In code you write, add a comment next to it with the same link.