Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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?

like image 563
Greg Gum Avatar asked Aug 13 '16 19:08

Greg Gum


People also ask

How do I merge two media queries?

Each media feature expression must be surrounded by parentheses. Logical operators can be used to compose a complex media query: not , and , and only . You can also combine multiple media queries into a single rule by separating them with commas.

How do you add max-width and maximum height in media query?

Use a comma to specify two (or more) different rules: @media screen and (max-width: 995px), screen and (max-height: 700px) { ... } Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others.

Should you use min-width or max-width in media query?

If you are designing your website for smaller devices first then set your initial breakpoints with min-width, whereas, if you are designing for larger devices first then use max-width. This post discusses min-width, and max-width media features in detail along with relevant examples.

Can we use multiple expressions in a media query?

A media query consists of a media type and can contain one or more expressions, which resolve to either true or false. The result of the query is true if the specified media type matches the type of device the document is being displayed on and all expressions in the media query are true.


2 Answers

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.

like image 133
zarcode Avatar answered Sep 20 '22 13:09

zarcode


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;
  }
}
like image 31
mukey Avatar answered Sep 20 '22 13:09

mukey