iocnsflow iocnsflow - 1 month ago 7
CSS Question

images in a banner disappear when I use max-width or width: auto

I have rotating banner images which I'd like to work (scale to fit) in any screen size.

When I use the following, it works:

.banner{
position:absolute;
width: 80%;
height: 30%;
top:5%;
left:20%;
background:#FFF;
border:hidden;
}


However, when I try to change the width to for example 40%, the images truncate rather than scale down.

When I tried to use, for example, max-width: 80%, or width: auto, the images totally disappear, even if I use a high z-index.

Answer

Setting both width and height on your images, will not care about aspect ratio. Just use width = 100%, and leave the height related to it (with the technique below).

And then set the container width to whatever you want:

#banner {
  width: 100%;
  height: 0;
  padding-top: 30%;
  background: red;
}

#banner-container {
  width: 400px;
}
<div id="banner-container">
    <div id="banner"></div>
</div>


If you want to show an image inside it, use CSS background-image with background-size: cover:

#banner {
  width: 100%;
  height: 0;
  padding-top: 30%;
  background: gray;
  background-position: 50% 50%;
  background-size: cover;
  background-repeat: no-repeat;
}

#banner-container {
  width: 400px;
}
<div id="banner-container">
    <div id="banner" style="background-image: url('http://placekitten.com/800/500');"></div>
</div>