The Cascade in Cascading Style Sheets can determine how a web page displays. The purpose of the Cascade is to resolve conflicts when more than one rule applies to an element on an HTML page. Factors such as specificity, inheritance, and the order of the rules within a style sheet can all affect the Cascade.
The most basic concept around the Cascade is the location of the style rule. Styles can be written in an external stylesheet, an internal stylesheet, or inline. In addition, each browser has built in default styles for HTML elements that determine formatting and appearance.
The general rule is “the closest style rules.” Rules cascade from browser defaults, external rules, internal rules, to inline rules. Each step down the cascade from browser defaults to inline rules brings the rule nearer and nearer to the HTML element it targets.
Here’s a paragraph with no styles attached. It displays according to the browser’s default styles.
Adding an external style sheet serves to illustrate the next step in the Cascade. I’ll add this rule to an external, linked stylesheet:
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
Here’s the result. You can see that the rules for font-family and color in the external stylesheet take precedence over the browser default rules.
The next step down through the Cascase into closer proximity to the affected HTML paragraph is to add an internal style rule to the document head.
This rule sets the paragraph to a purple color. Notice that the font-family set in the external style sheet is still Trebuchet, but the external rule regarding color has been overruled by the internal color rule.
The next step down in the Cascade is one that is not normally taken. It needs illustration, even though it is not a best practice and its use is discouraged. That is the inline style, a style rule written as an attribute of a single HTML element.
Here’s what I added to the <p> tag in the HTML document.
<p style="color: #F00">
The result is yet another color change. The inline red color rule takes precedence over the internal rule and the external rule. The font-family rule set in the external stylesheet remains unaffected.
These examples illustrate the principle of location of style rules in the Cascade. In practical terms, most web sites use only external stylesheets, and internal and inline styles don’t enter into the mix.
I plan to add future posts explaining factors that can affect conflicts in the Cascade when the only styles are in one or more external stylesheets. As I mentioned earlier in this post, that can include concepts such as the specificity of selectors and the order of the rules in the stylesheet. The order in which external stylesheets are linked to a page is also part of the Cascade.
One thought on “The Cascade by Example”