195

I'm trying to use CSS3 media queries to make a class that only appears when the width is greater than 400px and less than 900px. I know this is probably extremely simple and I am missing something obvious, but I can't figure it out. What I have come up with is the below code, appreciate any help.

@media (max-width:400px) and (min-width:900px) {
    .class {
        display: none;
    }
}
br.julien
  • 3,420
  • 2
  • 23
  • 44
russellsayshi
  • 2,449
  • 5
  • 17
  • 21

4 Answers4

353

You need to switch your values:

/* No less than 400px, no greater than 900px */
@media (min-width:400px) and (max-width:900px) {
    .foo {
        display:none;
    }
}​

Demo: http://jsfiddle.net/xf6gA/ (using background color, so it's easier to confirm)

Wylie
  • 350
  • 3
  • 12
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 5
    `max-width` and `min-width` should be reversed. this way is more readable – machineaddict Mar 12 '19 at 08:44
  • 2
    To clarify, `@media (max-width:X2) and (min-width:X1)` is the same as `X1 <= screen_size AND screen_size <= X2`. Also, it is better to write the `min-width` value first `@media (min-width:X1) and (max-width:X2)` because this is easier to read if a list of screen sizes has been provided (ie, `@media (min-width:X1) and (max-width:X2) { ... } @media (min-width:X3) and (max-width:X4) { ... } ...`) – Dave F May 03 '21 at 15:00
39

@Jonathan Sampson i think your solution is wrong if you use multiple @media.

You should use (min-width first):

@media screen and (min-width:400px) and (max-width:900px){
   ...
}
WalkerNuss
  • 435
  • 5
  • 9
  • 14
    The accepted answer is not wrong by any means, but I think that using min-width to max-width is a more clear, readable convention. – Dave Powers Dec 05 '17 at 16:46
  • 1
    Agree w/ @DavePowers. In my case, I had my media query formatted like @WalkerNuss, but had forgotten the first `and` after `@media screen`. Inserting the first `and` fixed this for me. – Kyle Vassella Mar 27 '18 at 17:10
10

just wanted to leave my .scss example here, I think its kinda best practice, especially I think if you do customization its nice to set the width only once! It is not clever to apply it everywhere, you will increase the human factor exponentially.

Im looking forward for your feedback!

// Set your parameters
$widthSmall: 768px;
$widthMedium: 992px;

// Prepare your "function"
@mixin in-between {
     @media (min-width:$widthSmall) and (max-width:$widthMedium) {
        @content;
     }
}


// Apply your "function"
main {
   @include in-between {
      //Do something between two media queries
      padding-bottom: 20px;
   }
}
JasParkety
  • 131
  • 1
  • 6
4

.class {
    display: none;
}
@media (min-width:400px) and (max-width:900px) {
    .class {
        display: block; /* just an example display property */
    }
}
Charlie
  • 41
  • 1