As mentioned on the previous page, there are a number of different style
sheets that a browser must take into consideration before applying styles to
a markup document. Browsers look through and
parse
the various style sheets in this order:
- Default browser style sheet.
- User defined style sheets (including browser preference settings).
- Author linked (external) style sheets.
- Author embedded styles.
- Author inline styles.
The Latest Declaration Wins!
Assume that we have a simple web page to which you have applied the following three style types, and they each contain conflicting P tag rules. The rules in these style sheets are as follows:
External style sheet
p { color: red; }
Embedded style sheet
p { color: green; }
Inline style
p { color: blue; }
As the browser begins parsing style sheets in the order of the cascade, all paragraphs are initially set to red based on the rule in the external style sheet.
But wait! The embedded style sheet's color of green conflicts with the declaration in the external style sheet because the same property/value (in this case, the P tag color) is being defined in both places. The embedded style sheet is closer to the content and is read after the external styles, so the embedded declaration wins! The text of every paragraph is now green.
Ah, but there's more. In this scenario a specific paragraph tag contains an inline style of blue, and inline styles trump all others. Therefore, this one specific paragraph becomes blue.
In this case the same element (the P tag) is being defined in multiple locations with exactly the same property but a different value. As the browser reads through the cascading order of the style sheets, the latest declaration wins.
The embedded declaration trumps the external style sheet's definition, and the inline declaration trumps the embedded definition. Easy and straightforward... the inline style is the last one read and the closest to the content which will be affected, so it wins and the text of that one paragraph is blue. The rest of the paragraphs are green.
What if it were more complicated?
Of course in the scenario above there was a single selector (the P tag, alone) and the various rules in the three different style sheets simply re-defined the same property/value (the color). What would happen if the rules were a little more complex?
Perhaps more than one rule applies differing colors to P tags within one style sheet by using contextual selectors, a universal selector, child, or adjacent sibling selectors. Which one 'wins?' Or, let's say your company's main external style sheet applies a particular color to paragraphs immediately following H3 tags, but in your department's external style sheet you need to change some or all of those same paragraphs to a different color. The following pages begin to shed light on ways to use the cascade and specificity to achieve the desired outcome without using embedded or inline styles.
Reference
- Wikipedia's definition of
"parse"