Avien
Avien

Reputation: 1260

Media query not seeming to work

Not sure why this isn't working. Any ideas?

When the screen goes below 700px the background color does not change and the HeaderImg is still displaying.

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <style>
    #content {
        text-align:center;
        width:100%;
        margin:0;
        padding:0;
    }

    img{
        height:auto;
        width: 100%;
    }

    @media only screen and (max-width: 700px) {
        #content{
            background-color:#000;
        }
        #HeaderImg{
            display:none;
        }
    }
    @media only screen and (max-width: 1920px) {
        #HeaderImg{
            display:inline;
        }
    }
    </style>
    </head>
    <div id="content">
        <img id="HeaderImg" src="LargeBanner_1920x300.png" width="600px" height="300px;"    />
    </div>

Upvotes: 0

Views: 41

Answers (1)

GolezTrol
GolezTrol

Reputation: 116110

That's because the second style overrules the first one. After all, less than 700px is also less than 1920px. Swap the two declarations, or specify a min-width as well for the second one, like this;

@media only screen and (min-width: 701px) and (max-width: 1920px) {
    #HeaderImg{
        display:inline;
    }
}

I would choose to specify the min-width. That way it's more clear what your intentions are, and there is no risk of accidentally applying properties to the <= 700px situation, that were actually only meant for the 701px to 1920px situation.

It should still change color, though. And it does, but you cannot see it, because the other issue is that the containing div (#content) will collapse once the image is hidden. It has no height, and therefor is not visible anymore. So to enforce the black bar being visible, you would have to give it an explicit height, or give it content of some sort. If you want it to occupy the space of the image, hide the image by using the stylevisibility instead of display. Visibility will show/hide the image, while still preserving the space it occupies in the document, and so the image will still stretch #content.

A dressed down, modified version of your snippet shows this:

#content {
  text-align:center;
  width:100%;
  margin:0;
  padding:0;
  /* Just for demo */
  color: red;
}

img{
  height:auto;
  width: 100%;
}

@media only screen and (max-width: 700px) {
  #content{
    background-color:#000;
  }
  #HeaderImg{
    visibility: hidden;
  }
}
@media only screen and (min-width: 701px) and (max-width: 1920px) {
  #HeaderImg{
    visibility: visible;
  }
}
<div id="content">
  <img id="HeaderImg" src="LargeBanner_1920x300.png" width="600px" height="300px;" alt="Test replacement for missing image">
</div>

Upvotes: 2

Related Questions