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:
- Importance (!important)
- Specificity (the selector specificity: an
id
more specific thanclass
element) What is the specificity ofbody #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:- Thousand if inside
style="..."
(rule directly inside the html attribute): 1000 - 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) - Ten for every class/attribute/pseudo-attribute in selector: here we have
:first-child
,[href$="..."]
and.active
so:3x10=30
- One for element selector : here we have
body
anda
so: 2x1 = 2 . Finally our grand total for this selector is : 1000 + 100 + 30 + 2 = 1132
- Thousand if inside
- 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.