Specificity¶
Specificity decides which selector wins when two rules have the same importance. It is often written as a three-part score:
Reading the score¶
- The id column beats everything to its right.
- The class column beats the type column.
- A later rule only wins when both rules have the same score.
One id beats any number of classes:
The #intro rule wins even if .lead comes later.
Keep specificity low¶
- Prefer classes.
- Avoid id selectors for styling.
- Do not nest selectors deeply.
- To override a rule, add another class rather than
!important.
/* base */
.btn {
padding: 0.5rem 1rem;
border: none;
}
/* variant, same specificity, later wins */
.btn-primary {
background: #0a58ca;
color: #fff;
}
A common mistake¶
If you later need a different colour for one link, you have to write an even more specific selector. Prefer:
Short selectors are easier to read and easier to override.
Try it¶
- Create a paragraph with
id="intro"andclass="lead". - Write a
prule, a.leadrule, and an#introrule, each with a different colour. - Predict which colour wins. Check in the browser.
- Remove the id rule and predict again.
- Rewrite the styles so the paragraph uses only a class and the result is still clear.
If you need a chain of ids and !important to change one element, simplify the selectors instead.
Next: Inheritance