</> Code Corner

CSS · CSS Tutorial · Lesson 39

CSS Specificity

Which rule wins when several match.

If two or more CSS rules point to the same element, the selector with the highest specificity wins.

Selector type Weight
Inline style 1-0-0-0
ID 0-1-0-0
Class, attribute, pseudo-class 0-0-1-0
Element, pseudo-element 0-0-0-1
Universal * 0

Example

<style>
#demo { color: blue; }
.test { color: green; }
p { color: red; }
</style>
<p id="demo" class="test">What color am I? (blue: the id wins)</p>
<p class="test">Green: class beats element</p>
Tip: If specificity is equal, the rule defined last wins. !important overrides everything — use it sparingly.

Keep reading “CSS Specificity”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋