4

I'd like for an image to only display when the viewport size is less than 768px.

When less than 768px, the image should span the entire width of the window and should not distort (i.e. height should change proportionally with the width).

However, right now, I can't get the height to change when I resize the window.

I've tried changing the display to block and specifying width:100%, height:auto.

HTML:

<div class="row col-12" id="mobileimg">
    <img src="images/img.png" alt="">
</div>

CSS:

#mobileimg {
    display:none;
}

@media only screen and (max-width: 768px) {

#mobileimg {
    display:flex;
    margin-top:20px;
}
}

Thanks!

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
traumerisch
  • 207
  • 1
  • 4
  • 10
  • check here -- http://stackoverflow.com/questions/12991351/css-force-image-resize-and-keep-aspect-ratio – Tasos Feb 15 '16 at 02:07
  • I tried that; scrollbars still appear after I set display to block, max-width to 768px, max-height to 200px, width:auto, and height:auto. – traumerisch Feb 15 '16 at 02:11
  • use (overflow: hidden;) to hide the scrollbars -- you can try the (object-fit) property -- https://css-tricks.com/almanac/properties/o/object-fit/ --- but Microsoft are considering its use – Tasos Feb 15 '16 at 02:14
  • Wouldn't overflow:hidden; only result in the image being cut off? I'd like the entire image to be shown. Object-fit doesn't seem to be working, either. – traumerisch Feb 15 '16 at 02:25
  • do a demo here -- https://jsfiddle.net/ -- and post the link in your Q – Tasos Feb 15 '16 at 02:27

1 Answers1

2

You need to set the dimensions on the image itself. That makes the image responsive. Try this:

#mobileimg {
  display: none;
}

@media screen and (max-width: 768px) {
  #mobileimg {
    display: flex;
    margin-top: 20px;
  }
  img {
    width: 100%;
    height: 100%;
  }
}
<div class="row col-12" id="mobileimg">
  <img src="http://lorempixel.com/400/200/" alt="">
</div>

jsFiddle demo

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • This worked--thank you so much!--but I'm confused as to /why it works. Why do I have to specify width/height:100% separately under a different selector (i.e. why can't it just be a declaration under #mobileimg)? – traumerisch Feb 15 '16 at 02:45
  • 2
    `#mobileimg` selects the div (the images' container). `img` selects the image itself. If you apply the `width` / `height` to the div, that doesn't tell the image anything. So we target the image directly. – Michael Benjamin Feb 15 '16 at 02:47