CSS specificity, Media Queries and min-width

I'm redesigning my blog with responsive web design in mind, and the "mobile first" method - In short I'm trying to use min-width to avoid any kind of replication or css.. no display:none's etc..

My problem is that when I do need to over-write a CSS value, the lower min-width takes precedence. Example:

@media only screen and (min-width: 600px) {
    h2 { font-size: 2.2em; }
}

@media only screen and (min-width: 320px) {
    h2 { font: normal 1.7em/2.1em Helvetica, sans-serif; }
}

I'd expect when I'm in resolutions of 600px and above to get a 2.2em h2, but instead I get 1.7em.. In my Dev tools I see that the 2.2em declaration is there, but the other one takes precedence.. It doesn't make sense!

Could I keep using min-widths and effectively overwrite declarations in higher resolutions without using stronger selectors or max-width..?


Solution 1:

I'd expect when I'm in resolutions of 600px and above to get a 2.2em h2, but instead I get 1.7em.. In my Dev tools I see that the 2.2em declaration is there, but the other one takes precedence.. It doesn't make sense!

It makes sense. If the media fulfills min-width: 600px, then it should also fulfill min-width: 320px; in other words, anything that's at least 600 pixels wide is also at least 320 pixels wide, because 600 is greater than 320.

Since both media queries evaluate to true, the rule that occurs last takes precedence in the cascade, making your code equivalent to this:

h2 { font-size: 2.2em; }
h2 { font: normal 1.7em/2.1em Helvetica, sans-serif; }

That explains why the 2.2em appears in your developer tools but doesn't take apparent effect.

The easiest fix is to switch your @media blocks around so your rules cascade in the correct order:

@media only screen and (min-width: 320px) {
    h2 { font: normal 1.7em/2.1em Helvetica, sans-serif; }
}

@media only screen and (min-width: 600px) {
    h2 { font-size: 2.2em; }
}