The "Importance" aspect of the CSS cascade dictates the hierarchy of style origins. Rules marked !important from user stylesheets take precedence over author !important rules, which in turn override normal author rules, user agent rules, and finally user agent !important rules. This hierarchy ensures a predictable order of application.
Example 1: User Agent vs. Author Normal
/* Browser's default stylesheet might have: */
/* h2 { font-weight: bold; } */
/* Your author stylesheet: */
h2 {
font-weight: normal; /* Author's normal rule overrides browser default */
color: green;
}
Explanation Your author's normal CSS rules (font-weight: normal;) will always override the browser's default (user agent) styles for the same property, as author styles have higher importance.
Example 2: Author Normal vs. Author !important
p {
color: blue; /* Normal author rule */
}
.special-paragraph {
color: orange !important; /* Author rule with !important */
}
/* HTML: <p class="special-paragraph">This text will be orange.</p> */
Explanation An !important declaration in your author stylesheet overrides any other normal declaration from your author stylesheet, even if the normal declaration has higher specificity.
Example 3: Inline Style vs. Author !important
<div style="background-color: yellow;">
<p class="highlight">This text will be red.</p>
</div>
/* Your author stylesheet */
.highlight {
background-color: red !important; /* This !important rule will override the inline style */
}
Explanation An author's !important rule overrides an inline style. This demonstrates the power of !important to force a style, but it should be used judiciously to avoid style conflicts.
Example 4: User !important vs. Author !important (Rare but possible)
/* Assumed user stylesheet rule (highly unlikely to be written by dev) */
/* body { font-family: 'Comic Sans MS' !important; } */
/* Your author stylesheet */
body {
font-family: Arial, sans-serif !important; /* This would be overridden by user !important */
}
Explanation In rare cases, a user's !important rule (e.g., from an accessibility extension) can override an author's !important rule. This prioritization is for user control over their Browse experience.
Example 5: Specificity within !important Rules
#unique-element {
background-color: blue !important; /* ID selector with !important */
}
.common-class {
background-color: green !important; /* Class selector with !important */
}
/* HTML: <div id="unique-element" class="common-class"></div> */
Explanation When multiple !important rules conflict, specificity still plays a role. The !important rule with the highest specificity (e.g., ID selector over class selector) will win.