matt
matt

Reputation: 44293

CSS: apply rule only in specific mediaquery?

following situation … 

/* @media screen and (min-width: 480px) */
@media screen and (min-width: 30em) {
     #el { background:red; }
}

/* @media screen and (min-width: 640px) */
@media screen and (min-width: 40em) {
     #el { background:none; }
}

So if the viewport is smaller than 480px #el should be red, if the viewport is wider it should have no background-color applied!

Is there some css trick to apply this rule only for min-width: 30em so I don't have to "reset" it in the next mediaquery?

Ideas and thoughts on that? Thank you in advance!

Upvotes: 1

Views: 890

Answers (2)

Suvi Vignarajah
Suvi Vignarajah

Reputation: 5788

If you want the background for #e1 to be red below a certain breakpoint, you should use max-width. If you want to apply styling rules for viewports that a greater than a certain breakpoint - that's when you should use min-width. In your example: @media screen and (min-width: 30em), the background will be red only when the viewport is larger than 30em - once it hits 40em it'll revert back to none (based on your other rule). In order to set the background for viewports smaller than 480px simply use max-width, you don't even have to worry about "resetting" because once the viewport exceeds 480px that rule will not apply.

/* @media screen and (max-width: 480px) */
@media screen and (max-width: 30em) {
    #el { background:red; }
}

Just remember, the rules you declare in min-width will apply to viewports that have a width greater than that breakpoint width you specify. Whereas rules declared in max-width will apply to viewports that are less/smaller than the breakpoint width.

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

Try in this way

@media screen and (min-width: 30em) and (max-width: 40em) {
     #el { background:red; }
}

example fiddle : http://jsfiddle.net/2ySNu/

Upvotes: 4

Related Questions