CSS Specificity
When two rules touch the same property on the same element, the browser has to pick one. Specificity is the score it uses to decide.
The specificity score
Read the score as four columns, highest column wins first; ties move to the next column.
!important overrides them all.Worked examples
| Selector | Score | Notes |
|---|---|---|
* | 0,0,0,0 | Universal — loses to everything. |
p | 0,0,0,1 | One type. |
.btn | 0,0,1,0 | One class — beats any number of types. |
a.btn:hover | 0,0,2,1 | One class + one pseudo-class + one type. |
#hero .title | 0,1,1,0 | One ID + one class. |
style="color:red" | 1,0,0,0 | Inline — beats everything except !important. |
Order of tiebreakers
- Importance — rules with
!importantwin first. - Specificity — higher score wins.
- Source order — when scores tie, the later rule wins.
Note:
!important is a hammer. Reach for it only when you can't restructure the selectors, otherwise specificity wars escalate quickly.Tip: Keep specificity flat. If your selectors look like
div.container nav ul li a.active, refactor — a single class on the right element is easier to maintain.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Specificity</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Force this rule to win, even if a class selector tries to override it later.
p { color: red
; }
It starts with an exclamation mark.
Discussion
Loading…