CSS: Cascade (rule priority)

By Xah Lee. Date: . Last updated: .

What is cascade

Cascade is the algorithm that determines which style rule has priority when multiple CSS rules apply.

example of rule clash

/* css rule clash */
p { color: red; }
.x { color: blue; }
<p class="x">what color am i</p>

Cascade priority order

Cascade priority is determined by this order. Here we start from lowest priority to highest.

Origin.

  1. Browser's style sheet file. (lowest)
  2. User's style sheet file.
  3. (the webpage) Author's style sheet file.
  4. Inline style (highest)

if tie (e.g. 2 rules are both in the webpage's style sheet), then we compare the next cascade.

Cascade layers

if tie (e.g. if there are no cascade layer defined or if 2 rules are in the same cascade layer), then we compare the next cascade.

Selector specificity

selectors priority ranking. e.g. id vs class vs tag name.

if tie, e.g. p {color:red} vs p {color:blue}, then we compare the next cascade.

Scope Proximity

Position in Source code

later rules in source code has higher priority.

The !important keyword

Example. Inline Styles vs Page Style

here, result is red, because inline style has higher priority in cascade than 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>

CSS cascade and scope