Introduction to the Cascade
Explore how CSS uses the cascade to manage conflicts when multiple style rules affect the same elements. Understand how rule order and hierarchy influence which styles are applied in web design.
We'll cover the following...
Cascading style sheets
What exactly does cascading mean? To answer this question, let’s start with an exercise.
Exercise
Add CSS, and write two rules:
- Select for
pelements, and give the rule acolorproperty with the valueblue. - For this rule, select for
pelements again, and give it acolorproperty with the valueorange.
Take a moment and answer the following question before proceeding further.
As shown by this example, order matters when creating CSS rules. If there are multiple CSS rules for the same element (and the same property), a hierarchical cascade is responsible for determining which one gets selected and applied to the element.
In the exercise you just did, the cascade selects the p element’s color based on the last rule present in the set of CSS rules. In other words, the second rule overwrites the first rule since they both select for the same element and the same property.
This cascade has a somewhat complex set of rules.
Test your understanding
What will happen if we include a div and a p element on an HTML page with the following CSS rule definitions?
div {
color: orange;
}
p {
color: blue;
}
Both div and p elements’ text will be blue since the cascade will select for the last rule present.
Both div and p elements’ text will be orange since the cascade will select for the first rule present.
The div element text will be colored orange and the p element text will be colored blue.
Neither the div nor the p elements’ text will be colored since the CSS definitions are not correct.