Why are CSS styles called cascading? When multiple rules are written that conflict with each other, the last rule written will be implemented. In this way, styles cascade downward and the last rule written is applied.
Let’s look at an example. Let’s write two CSS rules in an internal stylesheet that directly contradict each other.
<head>
<style>
p {color: red;}
p {color: blue;}
</style>
</head>
<body>
<p>What color will the text of this paragraph be?</p>
</body>
The browser will cascade through the styles and apply the last style encountered, overruling all previous styles. As a result, the heading is blue.
.code_sample_p {color: red;}
.code_sample_p {color: blue;}
What color will the text of this paragraph be?
This same cascading effect comes into play when using external stylesheets. It’s common for multiple external stylsheets to be used. When this happens, the style sheets are loaded in the order they appear in the HTML document head
element. Where conflicts between stylesheet rules occur, the CSS rules contained in each stylesheet will overrule those contained in previously loaded stylesheets. Take the following code for example:
<head>
<link rel="stylesheet" type="text/css" href="styles_1.css">
<link rel="stylesheet" type="text/css" href="styles_2.css">
</head>
The rules in styles_2.css will be applied if there are conflicts between the styles contained in these two stylesheets.
Inheritance of styles is another example of the cascading behavior of CSS styles.
When you define a style for a parent element the child elements receive the same styling. For example, if we apply color styling to an unordered list, the child list items will display the same styles.
<head>
<style>
ul {color: red;}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</body>
Here’s how that code would render..code-sample-ul {color: red;}
- Item 1
- Item 2
Not every property passes from a parent to its child elements. Browsers deem certain properties as non-inherited properties. Margins are one example of a property that isn’t passed down from a parent to a child element.