With this style
div {
@media (min-width: 0px) {
color: blue;
}
color: red;
}
<div>
hello
</div>
I expect the color to be red. However, it’s actually blue and I have no explanation for this. Tested on Chrome. The color is red in other browsers.
2
Answers
This is because the nested
@rule
actually unwraps toThis is explained in this paragraph of the specs, which even contains an example pointing out this case:
And if we do add the
&
selector to thecolor: red
rule, we get the same specificity:And note that your code currently produces a red output in non Chromium browsers because they still don’t support CSS nesting, so they just treat the
@media
rule here as an invalid rule and go on to parse thediv
one.If you want to support all browsers, you have to manually unwrap these rules:
I will use another example to illustrate your issue:
We are mixing "nested rules" and "declarations" and the Specification defines such behavior by moving the "nested rules" at the end.
So the browser will change your code to this:
And then to this:
So always start with the "declarations" then the "nested rules"