The Cascade is a fundamental element of CSS: it means that in order to fully understand how an element will be rendered, a developer should be aware of how weight, specificity, and order will affect the process.
In presence of multiple rules competing for the styling of an element, the browser chooses which one to use using a combination of how the rule was defined (with classes, id, HTML elements), and where (inline, internal style, external style, browser default, etc.).
Weight and Specificity
Given a CSS selector we can calculate the specificity by giving a weight to each element that is included in the selector itself:
- X – inline style attributes
- A – number of ID’s in the selector
- B – number of other attribute selectors, class selectors and pseudo-classes
- C – number of element names
Specificity is given by concatenating X.A.B.C where X has much more weight than A, A has much more weight than B, and so on. Some examples:
p a {...} /* specificity: 0.0.0.2 */
p.blue a {...} /* specificity: 0.0.1.2 */
.blue .link {...} /* specificity: 0.0.2.0 */
#sel .link {...} /* specificity: 0.1.1.0 */
/*
inline
<a style="..." href="..."></a>
specificity: 1.0.0.0
*/
I invite you to read the whole article in madisoft.labs