Can I use @media in an if/else kind of way?

Ahmad picture Ahmad · Jul 14, 2013 · Viewed 27.6k times · Source

I have this form placed in the footer of my page (has just one text box and one button). I want to try and apply @media to it, based on the viewport width available ... So for example, in my case the full width this form needs it about 270px or so. So I want to apply CSS to say that:

if the width available is at least 270px
     apply first set of CSS rules
else
     apply second set of CSS rules

How can I do this using @media ?

Answer

BoltClock picture BoltClock · Jul 14, 2013

There's no if/else syntax for @media, so you would need to repeat the same media query in two separate @media rules and use not for one of them to mean "else".

In your case, the media query would be all and (min-width: 270px). (You need to have a media type for not to work; the default is all so I'm just using that.)

Your CSS would then look like this:

@media all and (min-width: 270px) {
    /* Apply first set of CSS rules */
}

@media not all and (min-width: 270px) {
    /* Apply second set of CSS rules */
}

I should add that one popular way is to make use of the cascade by having just one @media rule for overriding styles:

/* Apply second set of CSS rules */

@media all and (min-width: 270px) {
    /* Apply first set of CSS rules */
}

However this falls short if you have any styles outside the @media rule that aren't (or cannot be) overridden inside it. Those styles would continue to apply, and you have no way of undoing them short of actually redeclaring them. Sometimes you cannot undo them by redeclaring them, and that's when you cannot use this method to apply styles. See my answer to this question for a detailed explanation.

In this example, the height: 200px declaration will always apply:

.example {
    width: 200px;
    height: 200px;
}

@media all and (min-width: 270px) {
    .example {
        width: 400px;
    }
}

Of course, if that's not a problem then you can use this in order to avoid duplicating media queries. But if you're looking for a strict if/else construct, then you'll have to use not and a duplicated media query.