Greg Gum
Greg Gum

Reputation: 38119

How to combine min-width and max-width in one media query

This media query is not working as I expected it to.

What I want to do is hide an element if the window is below 544px, and also hide it if it is above 767px. So it will only be visible while the window is between 544px and 767px.

@media (max-width: 544px) and (min-width: 767px) {
    .show-sm-only {
        display: none !important;
    }
 }

It seems that they work separately, but not together.

How do I achieve this?

Upvotes: 10

Views: 25416

Answers (3)

zarcode
zarcode

Reputation: 2485

You can combine two media queries in one, like this:

@media (max-width: 544px), (min-width: 767px) {
.show-sm-only {
    display: none !important;
}
}

EDIT This will hide .show-sm-only on screen smaller than (max-width) 544px and on screen bigger than (min-width) 767px.

Upvotes: 23

mukey
mukey

Reputation: 221

If you want a media query that is applied when BOTH conditions are true (which I think is what you're looking for here), use another and. Here it's hidden by default, and only visible when between 544px to 767px.

.my-element {
  display: none;

  @media (min-width: 544px) and (max-width: 767px) {
    display: block;
  }
}

Upvotes: 22

Nick Bull
Nick Bull

Reputation: 9876

You want this, your rules are the wrong way round. Right now you're saying it must be smaller than (max-width) 544px, but bigger than (min-width) 767px, which is impossible. See below how they are the other way round.

EDIT As per the comments. To do or (instead of and, which for your situation is impossible), separate with a comma:

@media (max-width: 544px), (min-width: 767px) {
    .show-sm-only {
        display: none !important;
    }
 }

Upvotes: 4

Related Questions