Before taking a deeper look at how cascade layers impact the cascade, let's look at an example involving multiple sources of CSS across the various origins, and work through the steps of the cascade algorithm:
Here we have a user agent stylesheet, two author stylesheets, and a user stylesheet, with no inline styles within the HTML:
User-agent CSS:
li {
margin-left: 10px;
}
Author CSS 1:
li {
margin-left: 0;
} /* This is a reset */
Author CSS 2:
@media screen {
li {
margin-left: 3px;
}
}
@media print {
li {
margin-left: 1px;
}
}
@layer namedLayer {
li {
margin-left: 5px;
}
}
User CSS:
.specific {
margin-left: 1em;
}
HTML:
<ul>
<li class="specific">1<sup>st</sup></li>
<li>2<sup>nd</sup></li>
</ul>
In this case, declarations inside li and .specific rules should apply.
Once again, there are five steps in the cascade algorithm, in order:
- Relevance
- Origin and importance
- Specificity
- Scoping proximity
- Order of appearance
The 1px is for print media. Due to lack of relevance based on its media type, it is removed from consideration.
No declaration is marked as !important, so the precedence order is author stylesheets over user stylesheets over user-agent stylesheet. Based on origin and importance, the 1em from the user stylesheet and the 10px from the user-agent stylesheet are removed from consideration.
Note that even though the user style on .specific of 1em has a higher specificity, it's a normal declaration in a user stylesheet. As such, it has a lower precedence than any author styles, and gets removed by the origin and importance step of the algorithm before specificity even comes into play.
There are three declarations in author stylesheets:
li {
margin-left: 0;
} /* from author css 1 */
@media screen {
li {
margin-left: 3px;
}
}
@layer namedLayer {
li {
margin-left: 5px;
}
}
The last one, the 5px is part of a cascade layer. Normal declarations in layers have lower precedence than normal styles not in a layer within the same origin type. This is also removed by step 2 of the algorithm, origin and importance.
This leaves the 0 and the 3px, which both have the same selector, hence the same specificity. Neither of them are inside a @scope block, so scoping proximity does not come into play in this example either.
We then look at order of appearance. The second one, the last of the two unlayered author styles, wins.
Note: The declaration defined in the user CSS, while it may have greater specificity, is not chosen as the cascade algorithm's origin and importance is applied before the specificity algorithm. The declaration defined in a cascade layer, though it may come later in the code, will not take precedence either as normal styles in cascade layers have less precedence than normal unlayered styles. Order of appearance only matters when both origin, importance, and specificity are equal.