Skip to content

CSS Tutorial CSS Specificity and the Cascade

Avoiding Specificity Problems

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

Almost all painful specificity bugs come from the same habits. Reverse them and the problems stop.

1. Style with classes

A class is strong enough to be useful and weak enough to be overridden. Avoid IDs for styling, since they jump the specificity ladder.

style.css
CSS
/* Hard to override later */
#sidebar .widget h3 { color: #d94a00; }

/* Easy to work with */
.widget-title { color: #d94a00; }

2. Keep selectors short

One class is ideal. Two is fine. A chain such as body .page .content .article ul li a is brittle: it breaks if the HTML changes, and the only way to beat it is a longer chain.

3. Do not qualify unnecessarily

ul.menu (0,1,1) is stronger than .menu (0,1,0). Both match the same elements. Pick the shorter one.

4. Do not use !important to win

See !important.

5. Use :where() for base styles

:where() adds no specificity, so styles inside it are the easiest to override.

style.css
CSS
:where(.prose a) { color: #1a5276; }  /* specificity (0,0,0) */
.btn { color: #fff; }                 /* wins without effort */

6. Order your CSS from general to specific

Resets and element styles first, then layout, then components, then variations and utilities. With equal specificity, later wins, so a good order stops most conflicts without any tricks.

7. Add a modifier class instead of a stronger selector

style.css
CSS
.btn { background: #1a5276; }
.btn--danger { background: #b00020; }  /* same strength, comes later */

A before-and-after example

index.html
HTML
<style>
  /* Fragile */
  /* div#page .box p.text { color: red; } */

  /* Resilient */
  .box__text { color: #1a5276; }
  .box__text--highlight { color: #d94a00; font-weight: bold; }
</style>
<div class="box"><p class="box__text">Normal text.</p><p class="box__text box__text--highlight">Highlighted text.</p></div>

The modifier overrides the base class simply because it comes later, with no extra specificity needed. More about this style of naming in Naming CSS Classes.

Exercise: fix the fight

The CSS #nav a { color: white; } is stopping a .nav-cta link from becoming orange. Without using !important or an ID, how would you restructure so .nav-cta can win?

Show a possible solution

Replace the ID rule with classes: .nav a { color: white; } and .nav .nav-cta { color: orange; }. Or better: .nav-link { color: white; } and .nav-link--cta { color: orange; }, with the modifier written after the base.