agyanadda@gmail.com

CSS Specificity

CSS Basics 1 min read Updated Dec 1, 2026 Topic 6 of 39

When two rules set the same property on one element, the browser picks the winner by specificity.

Specificity order (low to high)

  1. Element selectors (p, h1)
  2. Class, attribute and pseudo-class selectors (.btn, [type], :hover)
  3. ID selectors (#main)
  4. Inline styles (style="...")

If specificity is equal, the rule written later wins.

!important

color: red !important; beats normal rules. Avoid it — it makes CSS hard to change later.

Inheritance

Some properties (like color and font-family) pass from parent to child automatically. Others (like border and margin) do not.

Example

Example — Which colour wins? HTML
<style>
  p { color: gray; }
  .text { color: blue; }
  #special { color: green; }
</style>

<p>Gray (element)</p>
<p class="text">Blue (class beats element)</p>
<p class="text" id="special">Green (ID beats class)</p>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which selector has the highest specificity?

Exercise 2 True / False

When two rules have equal specificity, the one written later wins.

Exercise 3 Fill in the Blank

The keyword !___ makes a declaration override normal rules.

Frequently Asked Questions

Usually another rule with higher specificity wins. Open browser DevTools, inspect the element and see which rules are crossed out.