CSS - Cascading (style rules priority scheme)

1 - 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.

3 - Order of Precedence

3.1 - 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>

  • with a external Stylesheet such as Bootstrap (bootstrap.min.css), your custom declaration file (custom.css) must be placed after.

<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">
</head>

3.2 - Specificity

  • The HTML p element where two rules want to style it.

<p class="para">My beautiful paragraph will be blue</p>

  • The CSS. The last rule must win according to the cascade rule but as the selector is less specific than the first one, the first rule is applied

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.  */

  • The result:

3.3 - 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:

  • without the important rule, with a normal declaration

p { color: aqua }
p { color: red  }


<p>Hello, I'm red</p>

  • with the important rule

p { color: aqua ! important }
p { color: red  }


<p>Hello, I'm aqua</p>

4 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap