The Cascade, Inheritance & Specificity
When two rules fight over the same element, which one wins? Understand the rules so your CSS does what you expect.
What you will learn
- Understand inheritance and the cascade
- Calculate which selector is more specific
- Use !important responsibly
Inheritance
Some properties (like color and font-family) are inherited by children automatically. Set them on body and the whole page picks them up — unless overridden.
<style>
.card { color: #4338ca; font-family: sans-serif; }
</style>
<div class="card">
<h3>I inherit the colour and font</h3>
<p>So do I — even though no rule targets me directly.</p>
</div>The color and font-family are set only on .card, yet the <h3> and <p> inside it are also indigo and sans-serif. That is inheritance: certain text-related properties flow down from a parent to its children automatically. This is why setting font-family once on body styles the whole page. (Layout properties like border and padding are not inherited — only certain text ones are.)
The cascade & specificity
When multiple rules target the same element, the winner is decided by specificity — how specific the selector is:
| Selector type | Specificity (higher wins) |
|---|---|
Element p, div | Lowest |
Class .card, :hover, [type] | Medium |
ID #header | High |
Inline style="..." | Highest |
!important | Overrides everything (use sparingly) |
<style>
p { color: gray; } /* element — weakest */
.text { color: blue; } /* class — beats element */
#special { color: green; } /* id — beats class */
</style>
<p>Gray (element rule)</p>
<p class="text">Blue (class beats element)</p>
<p class="text" id="special">Green (id beats class)</p>All three rules try to set a paragraph’s colour, but each paragraph gets a different result based on which selector is most specific. The first paragraph matches only p (weakest), so it is grey. The second also matches .text — a class beats a plain element, so blue wins over grey. The third matches #special too — an id beats a class, so green wins over both. The rule of thumb: id beats class beats element, regardless of the order they are written in.
Watch out: !important forces a rule to win, but it makes CSS hard to maintain and override later. Treat it as a last resort, not a quick fix. Prefer a more specific selector instead.
Note: When two rules have the same specificity, the one written later in the CSS wins. So order matters too.
Q. Which selector wins when targeting the same element?
✍️ Practice
- Create three rules (element, class, id) for one element and predict which colour wins, then test.
- Fix a “not working” style by making the selector more specific instead of using
!important.
🏠 Homework
- Set
colorandfont-familyonbodyand confirm the whole page inherits them.