CSS Specificity

Which rule wins when several match.

✍️ 3 exercises + code challenge in this lesson

When several rules set the same property on an element, the browser uses specificity to decide which wins. From strongest to weakest:

  1. Inline styles (style="...")
  2. Id selectors (#nav)
  3. Classes, attributes and pseudo-classes (.menu, [type], :hover)
  4. Elements and pseudo-elements (p, ::before)

If two rules have equal specificity, the one written last wins.

!important overrides everything, but it makes CSS hard to maintain. Avoid it except as a last resort.

Key Takeaways: CSS Specificity

Mastering CSS Specificity helps you write clean and reliable CSS code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

CSS Specificity Code Example

CSS
<style>
  p           { color: gray; }
  .text       { color: #2563EB; }
  #intro      { color: #14B8A6; }
  p.text      { font-weight: bold; }
</style>

<p>Element selector: gray</p>
<p class="text">Class beats element: blue</p>
<p class="text" id="intro">Id beats class: teal</p>
<p class="text" id="intro" style="color: #E34F26;">Inline beats id: orange</p>
Free sign-in required · Google login available

CSS Specificity Practice Exercises

Check what you learned in “CSS Specificity”.

/ 3 solved
Fill in the blank

An id selector beats a class selector. Write the selector for id "main".

 { color: green; }
.text { color: red; }
✓ Correct! Not quite. Try again.
Multiple choice

Which selector is the most specific?

✓ Correct! Not quite. Try again.
Code challenge

The paragraph is red because of the id rule. Add a more specific rule (or inline style) so it becomes blue.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services