The "Order" in the CSS cascade refers to the sequence in which style rules appear in your stylesheets. When rules have the same origin and specificity, the last rule declared (lower down in the stylesheet or later in the link order) takes precedence. This is often called "source order."
Example 1: Basic Source Order
p {
color: red; /* First rule for paragraphs */
}
p {
color: blue; /* This rule comes later, so it overrides the red color */
}
Explanation This example clearly shows source order. Both p
selectors have the same specificity. Because the color: blue;
rule appears after color: red;
, it is applied.
Example 2: External Stylesheet Order
<link rel="stylesheet" href="styles1.css">
<link rel="stylesheet" href="styles2.css">
/* styles1.css */
.header {
font-size: 24px;
color: black;
}
/* styles2.css */
.header {
color: purple; /* This will override the black color from styles1.css */
border-bottom: 1px solid gray;
}
Explanation When multiple external stylesheets are linked, the styles from the last linked stylesheet in the HTML will take precedence for conflicting properties.
Example 3: Inline Styles vs. Internal/External Styles
<style>
/* Internal stylesheet */
.my-text {
font-size: 16px;
color: orange;
}
</style>
<p class="my-text" style="color: green;">
This text will be green.
</p>
Explanation Inline styles (defined directly in the HTML style
attribute) always have the highest order precedence among author styles, regardless of where your other CSS rules are defined.
Example 4: @import
Rule Order
/* main.css */
@import url("base.css"); /* Styles from base.css are loaded first */
.container {
width: 90%;
}
/* base.css */
.container {
padding: 10px;
background-color: #eee;
}
Explanation When using @import
, the imported stylesheet's rules are effectively placed at the @import
rule's position. So, rules defined directly in main.css
after the @import
will take precedence over conflicting rules in base.css
.
Example 5: Descendant Selector Order (Specificity vs. Order)
div p {
color: red; /* Less specific descendant selector */
}
.content p {
color: blue; /* More specific descendant selector due to class */
}
/* HTML: <div class="content"><p>This text will be blue.</p></div> */
Explanation While source order is important, specificity always wins first. In this case, .content p
is more specific than div p
, so its color: blue;
rule will be applied, regardless of the order they appear in the stylesheet.