1

I am attempting to utilize media queries to hide or unhide a div in HTML:

<div class="hide-medium hide-large">Test</div>

With the following CSS:

@media screen and (min-width: 994px){
    .hide-large{
        display:none
    }
}
@media screen and (max-width: 993px){
    .hide-medium{
        display:none
    }
}
@media screen and (max-width: 601px){
    .hide-small{
        display:none
    }
}

The div hides properly when the browser is sized accordingly; however when the browser size hits 601px and lower the div still stays hidden. What am I doing incorrectly?

Johannes
  • 64,305
  • 18
  • 73
  • 130
Elcid_91
  • 1,571
  • 4
  • 24
  • 50

1 Answers1

2

Media queries cascade. That is to say, at 601px your @media screen and (max-width: 601px) media query would correctly take affect, but the @media screen and (max-width: 993px) media query will also take affect, as 601px is smaller than 993px. Thus, the element has both media queries applied. And because your element still has the hide-medium class at a 'small' width, it will still be hidden.

If you don't want this to happen, I'd recommend explicitly setting a min-width on your middle media-query as well:

@media screen and (min-width: 994px) {
  .hide-large {
    display: none
  }
}

@media screen and (max-width: 993px) and (min-width: 602px) {
  .hide-medium {
    display: none
  }
}

@media screen and (max-width: 601px) {
  .hide-small {
    display: none
  }
}
<div class="hide-medium hide-large">Test</div>

It's also important to note that media queries in the same stylesheet are applied top-to-bottom. If you have a 'lower down' media query that has a valid rule for the target element, it will overwrite any valid media queries which are 'higher up'. You can make use off only min-width (mobile-first) or max-width (desktop-first) queries in this regard (without mixing them). This is further explained here.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71