iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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.

Inline style — 1,0,0,0 (always wins outside of !important) IDs — 0,1,0,0 per ID in the selector Classes / attrs / pseudo-classes — 0,0,1,0 each Types & pseudo-elements — 0,0,0,1 each (universal `*` = 0,0,0,0)
Fig 1. Higher columns dominate. !important overrides them all.

Worked examples

SelectorScoreNotes
*0,0,0,0Universal — loses to everything.
p0,0,0,1One type.
.btn0,0,1,0One class — beats any number of types.
a.btn:hover0,0,2,1One class + one pseudo-class + one type.
#hero .title0,1,1,0One ID + one class.
style="color:red"1,0,0,0Inline — beats everything except !important.

Order of tiebreakers

  1. Importance — rules with !important win first.
  2. Specificity — higher score wins.
  3. 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 &raquo;</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 ; }

Test yourself

Q1. Order these selectors from lowest to highest specificity.
Q2. Which declaration wins?
Q3. Why should `!important` be used sparingly?

Discussion

Loading…