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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)