Md Toy Blog

CSS cascade

Tue Feb 05 2019 00:00:00 GMT+0000 (Coordinated Universal Time)

Have you ever wondered how the cascading nature of Cascading Style Sheets really works ?

Don't take my word for it, cascading:

[…] indicates that the order of CSS rules matter […]. What selectors win out in the cascade depends on three factors Mozilla developer

Listed in order of precedence:

  1. Importance (!important)
  2. Specificity (the selector specificity: an id more specific than class element) What is the specificity of body #a-container:first-child > a[href$=".html"] .active ? We use the thousands, hundreds, tens, ones technique to count. The higher the final score the more specific it is. Examine the selector add a:
  3. Thousand if inside style="..." (rule directly inside the html attribute): 1000
  4. Hundred for every id inside the selector: here we have #a-container so 1x100=100. Note: it does not make sense to have more than one id since the childmost ID already selects the parent uniquely (but it should increase the specificity score)
  5. Ten for every class/attribute/pseudo-attribute in selector: here we have :first-child, [href$="..."] and .active so: 3x10=30
  6. One for element selector : here we have body and a so: 2x1 = 2 . Finally our grand total for this selector is : 1000 + 100 + 30 + 2 = 1132
  7. Source order (a the latest rule in source code overrides the earlier rule)

This means that in order to override an !important rule, you need to either :

  • create a rule of the same specificity later in the source code AND have the !important, or
  • add a rule earlier in the source code with a more specific selector AND have the !important keyword.

Since !important has the highest priority you need to use it combined with something else to win the battle.