Cascading
suggest changeCascading and specificity are used together to determine the final value of a CSS styling property. They also define the mechanisms for resolving conflicts in CSS rule sets.
CSS Loading order
Styles are read from the following sources, in this order:
- User Agent stylesheet (The styles supplied by the browser vendor)
- User stylesheet (The additional styling a user has set on his/her browser)
- Author stylesheet (Author here means the creator of the webpage/website)
- Maybe one or more
.cssfiles - In the
<style>element of the HTML document
- Inline styles (In the
styleattribute on an HTML element)
The browser will lookup the corresponding style(s) when rendering an element.
How are conflicts resolved?
When only one CSS rule set is trying to set a style for an element, then there is no conflict, and that rule set is used.
When multiple rule sets set conflicting values, specificity is applied first, and then cascade order breaks any remaining tie.
Example 1 - Specificity rules
.mystyle { color: blue; } /* specificity: 0, 0, 1, 0 */
div { color: red; } /* specificity: 0, 0, 0, 1 */
<div class="mystyle">Hello World</div>
The text is blue.
First the specificity rules are applied, and the one with the highest specificity “wins”.
Example 2 - Cascade rules with identical selectors
External css file
.class {
background: #FFF;
}
Internal css (in HTML file)
<style>
.class {
background: #000;
}
</style>
In this case, where you have identical selectors, the cascade kicks in, and determines that the last one loaded “wins”.
Example 3 - Cascade rules after Specificity rules
body > .mystyle { background-color: blue; } /* specificity: 0, 0, 1, 1 */
.otherstyle > div { background-color: red; } /* specificity: 0, 0, 1, 1 */
<body class="otherstyle">
<div class="mystyle">Hello World</div>
</body>
The background is red.
After applying the specificity rules, there’s still a conflict between blue and red, so the cascading rules are applied on top of the specificity rules. Cascading looks at the load order of the rules, whether inside the same .css file or in the collection of style sources. The last one loaded overrides any earlier ones. In this case, the .otherstyle > div rule “wins”.
A final note
- Selector specificity takes precedence over source order within the same origin and importance.
- Source order breaks ties between declarations of equal specificity.
- A normal inline style beats a normal author stylesheet rule. It does not beat an author
!importantdeclaration, and user-agent or user!importantrules can still win.