CSS allows us to give styles and design to our web page. It is important to understand how it works exactly to fully utilize its features. CSS stands for Cascading Style Sheet. Cascade means it is read and processed from top to bottom. In practice, styles written at the bottom of the CSS file will overwrite styles written before them. We are going to use paragraph elements to demonstrate the cascading effect.
language=>HTML
<p>This is a paragraph about something</p>
language=>CSS
p {
color: green;
}
We have established the natural behavior is that the text of the paragraph should be green, which is as shown above. What if we add another CSS rule set that targets the <p> element but set the color to red instead.
language=>CSS
p {
color: green;
}
p {
color: red;
}
The cascade will read both rule sets but the first one gets ignored. The paragraph text will be rendered in red. The browser is smart enough to only overwrite properties that overlap. If we add a property to the first rule set to change the font size of the text. This property will not be ignored.
language=>CSS
p {
font-size: 20px;
color: green;
}
p {
color: red;
}
The font size is larger and the color is red. Cascading also works when you have overlapping properties in the same ruleset.
language=>CSS
p {
font-size: 20px;
color: green;
color: red;
}
The result will be the same as above. Cascading also plays an effect when you have separate rule sets that target parent elements and its children elements. First, we are going to enclose our paragraph in a <div> element and add the color property to the div element and make its text content blue.
language=>HTML
<div>
<p>This is a paragraph about something</p>
</div>
language=>CSS
div {
color: blue;
}
The text is blue because <p> is a child of <div> and the CSS rule specifies that all children of <div> should have a text color of blue. We say that the child element is inheriting CSS rules from its parent element. Next, we add a rule that targets the <p> element and set the color to red.
language=>CSS
div {
color: blue;
}
p {
color: red;
}