CSS: cascade (rule priority, !important)

By Xah Lee. Date: .

What is cascade?

Cascade is the rules that decide which style has priority when multiple rules apply.

Cascade priority is determine by this priority list:

  1. Importance (by the declaration !important.)
  2. Origin. (e.g. inline style has higher priority, than page style, than external style file, than browser's style sheet.)
  3. Specificity (selectors priority ranking. e.g. id vs tagname vs class.)
  4. Source order (what comes last)

Inline Styles vs Page Style

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />

  <title>style test</title>

 <style> #x5653 { color: blue; } </style>

 </head>
 <body>
  <main>
   <h1>style test</h1>

   <p id="x5653" style="color: red">what color am I?</p>
  </main>
 </body>
</html>

result is red, because inline style has higher priority in cascade than page style.

The !important keyword

the !important has highest cascade priority.

when two rules are both !important, the one with higher specificity or later in the cascade, wins.

p {
 color: red !important;
}

/* beats everything below */

#id8383 .xclass p {
 color: blue;
}

🛑 WARNING: do not use the !important, because it makes your CSS hard to maintain once you have more than one.

CSS, misc, advanced