CSS Intermediate: Layout and Responsive Design
The Cascade, Specificity and Inheritance
In this lesson you will
- Explain how the cascade chooses between competing rules
- Compare the specificity of two selectors
- Describe which properties are inherited
Introduction
Sooner or later you write a rule, nothing changes, and you wonder why. Usually another rule is winning. The "C" in CSS stands for Cascading: it is the system the browser uses to settle such conflicts. Learn it once and a lot of confusion disappears.
Rule 1: later wins (when equal)
If two rules have the same weight, the one written later wins.
Rule 2: more specific wins
A more specific selector beats a less specific one, no matter the order. From weakest to strongest:
- Element selectors (
p) and pseudo-elements - Class selectors (
.note), attributes and pseudo-classes (:hover) - Id selectors (
#intro) - Inline styles (the
styleattribute)
Quick quiz
A paragraph has id=intro and class=note. Both have a colour rule. Which colour is used?
Counting specificity
Think of specificity as three numbers: (ids, classes, elements).
pis (0, 0, 1).noteis (0, 1, 0)p.noteis (0, 1, 1)#intro .note pis (1, 1, 1)
Compare from left to right. One id beats any number of classes.
The !important trap
!important overrides almost everything, which sounds handy but causes trouble. Once you use it, the only way to beat it is another !important. Treat it as a last resort and fix the underlying specificity instead.
Inheritance
Some properties are inherited: a child element uses its parent's value if you do not set its own. Text properties such as color, font-family, font-size and line-height are inherited. Box properties such as margin, padding and border are not.
You can force inheritance with inherit, or undo your changes with initial and unset.
Tips for easy-to-manage CSS
- Style with classes, not ids.
- Keep selectors short. Avoid long chains like
div .a .b p. - Do not use
!importantto win fights. - Put general rules first and specific rules later.
Quick quiz
Which property is inherited by default?
Try it yourself
Make the paragraph green without using !important or changing the order. Hint: use a selector with higher specificity than .note, such as p.note.
Summary
- When rules conflict, the cascade picks one: more specific first, then later.
- Specificity order: element, class, id, inline.
- Avoid
!important. - Text properties are inherited. Box properties are not.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading