CSS Specificity ยท Astro Tech Blog

Specificity

When multiple CSS rules match the same element, specificity decides which one applies. Each selector type has a weight:

Specificity Hierarchy

LevelExamplesWeight
Inline stylesstyle="..."1,0,0,0
IDs#header0,1,0,0
Classes, attributes, pseudo-classes.class, [type], :hover0,0,1,0
Elements, pseudo-elementsdiv, ::before0,0,0,1
Demo: Specificity Battle
HTML
<div id="box" class="highlight" style="color: #7c3aed;">
Which color wins?
</div>
CSS
div { color: #64748b; }
.highlight { color: #f59e0b; }
#box { color: #059669; }
Live Output Window

Inline styles win โ€” but avoid them. Use classes for clean, maintainable specificity.

Calculating Specificity

p           โ†’ 0,0,0,1
.highlight  โ†’ 0,0,1,0
#header     โ†’ 0,1,0,0
#header p   โ†’ 0,1,0,1

!important

!important overrides specificity entirely. Use it sparingly:

Demo: !important Example
HTML
<p class="override">This is important!</p>
CSS
p { color: #64748b !important; }
.override { color: #ef4444; } /* loses to !important */
Live Output Window