Why does the order of css selectors matter?
Here is example 1 ( jsfiddle ):
HTML:
<div class="class_1 class_2">
This is a text
</div>
CSS
.class_1 {
font-size: 1em;
color: blue;
}
.class_2 {
font-size: 2em;
}
This works as I expect. I have <div class="class_1 class_2">
both the result color
from class_1
and font-size
from class_2
. As far as I understand, the rule font-size
in class_2
replaces the rule font-size
out class_1
.
Here is example 2 ( jsfiddle ).
It has the same html:
<div class="class_1 class_2">
This is a text
</div>
But the css selectors are in reverse order:
.class_2 {
font-size: 2em;
}
.class_1 {
font-size: 1em;
color: blue;
}
And this code doesn't work as I expect. I expose it to work example 1. But only the rules from class_1
. I wrote
<div class="class_1 class_2">
and I expect the rules from class_1
will be applied and then they will be changed to class_2
.
Why is this happening? What is the rule that makes css this way?
source to share
For selectors that have the same specificity, the rules are applied in the order in which they appear in the CSS file (or in files if there are more than one). The order of the CSS classes specified in the HTML attribute class
does not matter.
This means that in the second example, the rules for are first applied .class_2
, followed by the rules for .class_1
. As a result, when any attribute is defined in both blocks, the rules in the second block override the rules in the first when both classes are present in the element.
So, the rules from both blocks were applied! (Add an attribute color
to the block .class_2
to prove it to yourself.) But after the block was applied .class_2
, the block .class_1
was - and it also defines an attribute font-size
that replaces the same attribute defined in .class_2
.
source to share