Specificity management
Learn specificity calculation and management.
How is specificity calculated?
Specificity is a triple that marks a selector's power level: (a, b, c). Here a counts ids, b counts classes and attributes, c counts type selectors. The higher column wins first: (1, 0, 0) beats (0, 5, 5).
Example: #main .card h2 has specificity (1, 1, 1) — one id, one class, one type. .card h2 has (0, 1, 1). Adding an id bumps a, not b, so a single id outranks any number of classes.
!important and its risks
Adding !important to a declaration makes it win regardless of specificity. The form: color: red !important; — exclamation, space, the word important. It looks tempting but is not a real fix.
The reason is simple: once you add !important, overriding it later needs another !important with higher specificity. Soon the file turns into a pile of !important flags and tracing which declaration wins becomes impossible. Manage specificity first.
Strategies to lower specificity
High specificity makes later changes hard. Ways to keep it low: prefer classes over ids, replace type selectors with classes, avoid nested selectors. Writing .card-title instead of #main .card h2 drops specificity from (1, 1, 1) to (0, 1, 0).
Naming methods like BEM make this easy: each class is a flat class, no nesting, specificity stays at (0, 1, 0). Reuse also improves; the same class works inside another block.
Exercise Simplify the complex selector
Replace the high-specificity selector with a lower-specificity BEM class. Add a new .card__title class selector and put font-size: 1.5rem and color: navy inside it. Add nothing else.
Show example solution
/* write a BEM class instead of #main .card h2 { color: navy; } */
.card__title {
font-size: 1.5rem;
color: navy;
}
Test yourself
-
Which selector has the highest specificity?
#nav .menu a .menu .item a div nav a #nav ul li.active- #nav .menu a
- .menu .item a
- div nav a
- #nav ul li.active
Show answer
#nav ul li.active — Correct. #nav ul li.active has specificity (1, 1, 2); the last column's 2 beats the other (1,1,1).
-
Strengthen the declaration with !important
.alert { color: red; font-weight: bold ____ }Show answer
.alert { color: red; font-weight: bold !important; } -
Match each selector to its specificity
- #main
- (1, 0, 0)
- .card .title
- (0, 2, 0)
- nav ul li
- (0, 0, 3)
- #nav .item a
- (1, 1, 1)