Reputation: 1581
In my CSS I have the following:
.myDiv{
float:left;
width:100px;
height:100px;
}
.yellow{
background:#faf8c7;
}
.lightGrey{
background:#f8f8f8;
}
In my HTML
<div class="myDiv lightGrey yellow"></div>
This should display the div
as the yellow colour but instead it is lightGrey.
If I change the order of the .yellow and .lightGrey in my CSS (not HTML) then the div
becomes yellow...why is this?
Surely it should be the order that the classes are written in the HTML that determines whether the div
is yellow or grey. The order of the CSS should be irrelevant.
Upvotes: 1
Views: 69
Reputation: 123387
since all rules have the same specificity, the last one (for the meaning of Cascade) specified in the CSS
wins. In other words, no matter you re-arrange your classes in the markup, with the given style your background is always lightgray.
Surely it should be the order that the classes are written in the HTML that determines whether the div is yellow or grey. The order of the CSS should be irrelevant.
for the above explanation it's the opposite
Upvotes: 0
Reputation: 179046
surely it should be the order that the classes are written in the html that determines whether the div is yellow or grey
It's how the cascade was defined:
- Find all declarations that apply to the element and property in question, for the target media type. Declarations apply if the associated selector matches the element in question and the target medium matches the media list on all @media rules containing the declaration and on all links on the path through which the style sheet was reached.
- Sort according to importance (normal or important) and origin (author, user, or user agent). In ascending order of precedence:
- user agent declarations
- user normal declarations
- author normal declarations
- author important declarations
- user important declarations
- Sort rules with the same importance and origin by specificity of selector: more specific selectors will override more general ones. Pseudo-elements and pseudo-classes are counted as normal elements and classes, respectively.
- Finally, sort by order specified: if two declarations have the same weight, origin and specificity, the latter specified wins. Declarations in imported style sheets are considered to be before any declarations in the style sheet itself.
#4 is the part you're struggling with, the declarations have identical specificity, and therefore the latter one is winning.
Upvotes: 8
Reputation: 8392
order in your html code of each class myDiv lightGrey yellow
is not important at all, it's like you say : I bought 3 colors, but we don't know what is the first or the last you bought
Upvotes: 0
Reputation: 22947
Cascading Style Sheet.
That means that style that appears later in the stylesheet will overwrite style that appeared earlier in the sheet.
Upvotes: 1