Skip to content

CSS Tutorial CSS Specificity and the Cascade

CSS Specificity

Lesson 161 of 182 2 min read By Deepak Paswan Updated Oct 4, 2026

Sooner or later two rules will aim at the same element and disagree.

index.html
HTML
<style>
  p { color: green; }
  .note { color: blue; }
  #intro { color: red; }
</style>
<p id="intro" class="note">What color am I?</p>

The text is red, although the p rule is first and .note is in the middle. The browser compares how specific each selector is, and the most specific one wins. That is specificity.

The ranking

From weakest to strongest:

LevelExampleWeight
Universal and combinators*0
Element or pseudo-elementp, ::beforelowest (0,0,1)
Class, attribute, pseudo-class.note, [type="text"], :hovermiddle (0,1,0)
ID#introhigh (1,0,0)
Inline style attributestyle="color: red"higher still

Counting it

Write specificity as three numbers: (IDs, classes, elements).

SelectorSpecificity
p(0, 0, 1)
p.note(0, 1, 1)
.note(0, 1, 0)
nav ul li a(0, 0, 4)
#menu a:hover(1, 1, 1)
#intro(1, 0, 0)

You compare from left to right. One ID beats any number of classes. One class beats any number of elements. So .note (0,1,0) beats nav ul li a (0,0,4), even though the second selector is longer.

Equal specificity: the later rule wins

If two selectors tie, the one written later in the stylesheet wins. This is why link states have an order.

index.html
HTML
<style>
  .box { background: #d0e8f2; padding: 12px; }
  .box { background: #fdebd9; }
</style>
<div class="box">The second rule wins: it comes later.</div>

Using the developer tools

When a style does not apply, the Styles panel shows crossed-out rules. Find the rule that won: it is the one that is not struck through. Compare the specificity of the two. See Developer Tools.

lightbulb
Do not count by hand every time
Use the rule of thumb: IDs beat classes, classes beat elements, inline beats most, later beats earlier. For anything stranger, the developer tools will show you.

Next: how !important breaks the order, and the full list of what the browser checks in The Cascade.