🌱BeginnerCSS Foundations

CSS Cascade and Specificity

Understand how the CSS cascade resolves conflicting rules using specificity, source order, and importance.

Overview

When two or more CSS rules target the same element and set the same property, the browser must decide which one wins. This decision process is called the cascade. 1. **Importance** Rules marked with `!important` override all other rules. 2. **Specificity** The more specific the selector, the higher its priority. IDs (1,0,0) > Classes (0,1,0) > Elements (0,0,1). 3. **Source Order** When specificity is equal, the rule that appears later wins. Understanding specificity prevents frustrating bugs where styles seem to be "ignored".

Key Points

  • •!important overrides everything avoid it except as a last resort
  • •Higher specificity wins when two rules conflict on the same property
  • •IDs (1,0,0) > Classes/Attributes/Pseudo-classes (0,1,0) > Elements (0,0,1)
  • •Source order: when specificity is tied, the later rule wins
  • •Inline styles have even higher specificity than any selector
  • •The universal selector (*) and combinators have zero specificity

Examples

Specificity comparison

p       { color: black; }   /* (0,0,1) */
.intro  { color: blue;  }   /* (0,1,0) wins over p */
#main   { color: green; }   /* (1,0,0) wins over .intro */

Source order wins on equal specificity

.btn { background: blue; }   /* loses */
.btn { background: red;  }   /* wins later in source */

!important last resort override

p { color: red !important; }
/* Even inline style="color:green" is overridden */

Common Mistakes

  • Adding !important everywhere to "fix" specificity the real fix is writing less-specific selectors
  • Using deep selectors like #nav > ul > li > a when a class would be simpler
  • Not realizing an inline style is overriding your stylesheet

Note

When a style is not applying, open DevTools and look at the Computed tab. Crossed-out rules have been overridden.

Exercises

Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What is the correct specificity order from lowest to highest?