Nick
Nick

Reputation: 2911

CSS Media Query multiple ranges

I have a requirement where a CSS rule applies between 2 ranges and then above a breakpoint. For example: I need my background to be green, unless the width is 750-800, 850-900 or 900+.

I have tried the following but it does not seem to work:

.foo { 
    background: green
}

@media all
  and (
    ((min-width: 750px) and (max-width: 800px)),
    ((min-width: 850px) and (max-width: 900px)),
    (min-width: 950px)
  ) {
    .foo {
        background: red;
    }
}

See: http://jsfiddle.net/njt1982/c2a0yuLh/

If my browser width were 775px then both criteria are met, aren't they? (I am "all" and I am within the first range).

Is what I want to do even possibe?

Update

I found a method below: https://stackoverflow.com/a/33786265/224707 However it involved repeating the "all and" part. Is there any way to "group" parts? eg x AND (y OR z)?

Upvotes: 1

Views: 3356

Answers (2)

justinw
justinw

Reputation: 3966

Your syntax was incorrect. You were adding another set of () to your @media rule.

DEMO

Also, you don't need to explicitly state all, the lack a media-type define is implied as all - docs

div {
    background: green;
}

@media
    (min-width: 650px) and (max-width: 700px),
    (min-width: 750px) and (max-width: 800px),
    (min-width: 850px) {
    
    div {
        background: red;
    }
    
}
<div>div</div>

Upvotes: 5

Nick
Nick

Reputation: 2911

As per usual, I spend ages on something only to figure it out moments after asking...

.foo { 
    background: green
}

@media all and (min-width: 750px) and (max-width: 800px),
       all and (min-width: 850px) and (max-width: 900px),
       all and (min-width: 950px) {
    .foo {
        background: red;
    }
}

See: http://jsfiddle.net/njt1982/zyjnvjpz/

Upvotes: 2

Related Questions