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:

  1. X – inline style attributes
  2. A – number of ID’s in the selector
  3. B – number of other attribute selectors, class selectors and pseudo-classes
  4. 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

write forMadisoft Labs

About the author

For the last 15 years, Stefano Frasca has worked with a variety of web technologies both backend and frontend. He is currently focused on front-end development. On his day to day job, he is working as a FullStack developer & Frontend specialist at Maestrale IT. He has worked remotely for years, passionate about photography, food and code 😎
Do you want to know more? Visit my website!