Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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.

like image 976
iocnsflow Avatar asked Dec 20 '25 17:12

iocnsflow


1 Answers

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>
like image 149
dashtinejad Avatar answered Dec 23 '25 07:12

dashtinejad