Table of Contents

CSS - Cascading (style rules priority scheme)

About

CSS specifies a priority scheme to determine which style rules apply if more than one rule matches against a particular element. In this so-called cascade, priorities or weights are calculated and assigned to rules, so that the results are predictable.

While the author of a document typically links that document to a CSS stylesheet, readers can use a different stylesheet, perhaps one on their own computer, to override the one the author has specified.

Order of Precedence

Position

Selector matches cascade from the top down. When more than one same selector applies to an element, the later rule overrides the earlier one.

The last rule in the css rule processing with the same selector is chosen.

Example:

p { color: red  }
p { color: blue}
<p>Hello, I'm blue and not red</p>
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">
</head>

Specificity

<p class="para">My beautiful paragraph will be blue</p>
p.para { color:blue; } /* I will win because I'm the most specific rule */
p { color:red; } /* I want it red and I'm the last one. According to the cascade rule, 
 I must win but unfortunately, I'm less specific the I lose.  */

Important

An important rules takes precedence over a normal declaration.

The use of important is no more needed if you scope your dom in a shadow dom

Syntax: ! important after a normal declaration:

p { color: aqua ! important }

Example:

p { color: aqua }
p { color: red  }
<p>Hello, I'm red</p>
p { color: aqua ! important }
p { color: red  }
<p>Hello, I'm aqua</p>

Documentation / Reference