In what order are CSS rules applied?
CSS rules are applied in a strictly defined order, and the browser picks the final style based on three levels of priority, from top to bottom:
1) Style source (the largest priority level)
From strongest to weakest:
!important(manually boosted priority)- inline styles (the
style=""attribute) - external and internal styles (
.cssfiles and<style>) - default browser styles
2) Specificity (selector precision)
If rules belong to the same source, the selector is examined. From more precise to less precise:
- ID:
#header - Classes, attributes, pseudo-classes:
.item,[type="text"],:hover - Tags and pseudo-elements:
p,h1,::after
3) Order in the code (the last word goes to the lower selector)
If the source and specificity are the same, the rule that is written later wins:
css
p { color: blue; }
p { color: black; } /* this one will apply */The final cascade formula
The browser decides like this:
importance → specificity → order in the code
That is, sources are compared first, then selector precision, and only if they are equal is the last rule in order taken.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.