Reading history

CSS Specificity and the Cascade Explained

6 min read 3 views

Find out why one CSS rule beats another: specificity scores, source order, inline styles, !important, inheritance and the inherit and unset keywords, with live examples.

Sometimes several CSS rules try to style the same element: one says the text is green, another says purple. Which one wins? The browser decides with a set of rules called the cascade, and the most important part of it is specificity, a score for how precisely a selector targets an element. Understanding these rules ends the frustration of “why is my CSS not working?”.

In this lesson you will learn

  • How the cascade chooses between competing rules
  • Calculating specificity as (ID, class, type)
  • Source order as the tie-breaker
  • Inline styles and !important
  • Inheritance and the inherit, initial and unset keywords

You should know CSS selectors and pseudo-classes.

Specificity

Each selector gets a score with three parts, written (A, B, C):

PartCountsExample
AID selectors#intro → (1, 0, 0)
BClasses, attributes and pseudo-classes.note, [type="text"], :hover → (0, 1, 0)
CElement (type) selectors and pseudo-elementsp, ::before → (0, 0, 1)

Scores are compared from left to right, like comparing numbers digit by digit. One ID beats any number of classes, and one class beats any number of element selectors.

p                    (0, 0, 1)
div p                (0, 0, 2)
.note                (0, 1, 0)
div p.note           (0, 1, 2)
nav a:hover          (0, 1, 2)
#intro               (1, 0, 0)
#menu .item a        (1, 1, 1)
*                    (0, 0, 0)   the universal selector adds nothing
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Specificity</title>
  <style>
    body { font-family: sans-serif; margin: 12px; font-size: 14px; }
    p { color: gray; }                    /* (0,0,1) */
    .note { color: green; }               /* (0,1,0)  beats p */
    #intro { color: purple; }             /* (1,0,0)  beats any number of classes */
    div p.note { color: orange; }         /* (0,1,2)  beats .note alone */
    .later { color: blue; }
    .later { color: crimson; }            /* same specificity: the last rule wins */
  </style>
</head>
<body>
  <p>Plain paragraph: gray (type selector)</p>
  <p class="note">class="note": green</p>
  <p class="note" id="intro">id="intro" wins: purple</p>
  <div><p class="note">div p.note: orange</p></div>
  <p class="later">Two equal rules: the later one, crimson</p>
  <p class="note" style="color: teal">Inline style beats them all: teal</p>
</body>
</html>

Result

  • The plain paragraph matches only p, so it is gray.
  • .note (0, 1, 0) beats p (0, 0, 1), so the second line is green.
  • The third line matches p, .note and #intro; the ID has the highest score, so it is purple.
  • div p.note (0, 1, 2) beats .note (0, 1, 0) because they tie on classes and it has more element selectors.
  • When two rules have equal specificity, the one written later wins, so the fifth line is crimson.
  • An inline style attribute beats every selector in a stylesheet.

The Cascade, Step by Step

When rules conflict, the browser checks these in order and stops at the first difference:

  1. Importance: declarations marked !important win over normal ones.
  2. Origin and layers: your stylesheet beats the browser’s default styles; later @layers beat earlier ones.
  3. Specificity: the higher score wins (inline styles count highest).
  4. Source order: the rule that appears last wins.

Inheritance and Keywords

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Cascade and inheritance</title>
  <style>
    body { font-family: sans-serif; margin: 12px; font-size: 14px; color: #1b5e20; }
    .card { border: 2px solid #ccc; padding: 8px; margin-bottom: 8px; }
    .card a { color: inherit; }                  /* force the link to take its parent's colour */
    .box { border: inherit; padding: 4px; }      /* border is not inherited unless asked */
    .warn { color: red !important; }             /* !important jumps above normal rules */
    #main .warn { color: blue; }                 /* higher specificity, but loses to !important */
    .reset { all: unset; display: block; font-family: monospace; }
  </style>
</head>
<body>
  <div class="card">Text inherits the body colour. <a href="#">This link inherits too.</a>
    <div class="box">Inner box borrows the card's border</div>
  </div>
  <div id="main"><p class="warn">!important wins: red</p></div>
  <p class="reset">all: unset clears the default margins and styles of p</p>
</body>
</html>

Result

  • Some properties are inherited from the parent when an element has no value of its own, mainly text properties such as color, font-family and line-height. Others, such as border, margin and background, are not.
  • Links have their own colour from the browser, so they do not inherit it. color: inherit forces them to.
  • border: inherit makes the inner box copy its parent’s border, which it would not do by itself.
  • !important made the text red even though #main .warn has a higher specificity. That power is also its danger: the only way to beat it is another !important.
  • all: unset resets every property: inherited ones go back to inheriting and the rest return to their initial values, removing the paragraph’s default margins.

Keeping Specificity Under Control

  • Style mostly with single classes, so scores stay low and equal.
  • Avoid IDs in CSS; keep them for links and JavaScript.
  • Do not chain long selectors such as body div.main ul li a.
  • Use !important only for utility classes or to override third-party styles you cannot edit.

Common Mistakes

  1. Adding !important everywhere, which starts an arms race of more !important.
  2. Thinking 11 classes beat one ID. They do not: columns never carry over.
  3. Forgetting source order when two rules have the same score.
  4. Expecting margin or border to be inherited.

Practice Exercises

Exercise 1. Calculate the specificity of ul#nav li.active > a.

Show answer

One ID (#nav), one class (.active), three elements (ul, li, a): (1, 1, 3).

Exercise 2. .btn { color: white; } is not working because #header a { color: black; } also matches. Fix it without !important.

Show answer

Raise the specificity just enough, for example #header .btn { color: white; } (1, 1, 0), or better, remove the ID from the header rule so both are class-based.

Frequently Asked Questions

How can I see which rule is winning?

Right-click the element and choose Inspect. The Styles panel lists every matching rule in order of priority and strikes through the declarations that lost.

What are cascade layers?

The @layer rule groups styles into named layers, such as reset, base and components. A later layer wins over an earlier one regardless of specificity, which makes large stylesheets easier to organise.

Summary

  • Specificity is scored (IDs, classes, elements) and compared left to right.
  • Equal specificity: the later rule wins. Inline styles beat stylesheets.
  • !important overrides normal rules; use it rarely.
  • Text properties inherit; box properties do not unless you use inherit.

Next: CSS Transforms.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *