CSS-16Recommended
Select elements by their own class
Select elements in a component by their own class, never by tag name, position or ancestry. A selector has at most 2 compound parts and 0 type selectors in the components layer, which keeps it inside the 0,2,0 cap.
How to do it
A selector like .order-card div > span:nth-child(2) breaks when someone adds a wrapper or moves a line. Give the element a class instead, and let Cap selector specificity and keep ids out of selectors keep the weight low. Positional pseudo-classes are fine for repeating patterns such as zebra rows in the base layer.
Examples
CSS example
/* Avoid: breaks when the markup changes */
.order-card div > span:nth-child(2) { }
/* Do: the element names itself */
.order-card-price { }
JSON example
{
"overrides": [
{
"files": ["styles/components/**/*.css"],
"rules": {
"selector-max-compound-selectors": 2,
"selector-max-type": 0,
"selector-pseudo-class-disallowed-list": ["nth-child", "nth-of-type", "first-child", "last-child"]
}
}
]
}
How to check
In the components folder, the linter rules selector-max-compound-selectors set to 2 and selector-max-type set to 0 report 0 problems. A search finds 0 uses of :nth-child, :nth-of-type, :first-child or :last-child there.
Sources
Related rules
- CSS-7 Cap selector specificity and keep ids out of selectors in HTML and CSS
- CSS-33 Nest only states and queries one level deep in HTML and CSS
- CSS-23 Avoid wrapper elements that only hold a class 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/naming-and-state/no-position-selectors">Agent Wranglers HTML and CSS playbook</a>. In code you write, add a comment next to it with the same link.