Jackymamouth Jackymamouth - 1 year ago 75
HTML Question

Background size : contain

I would like a div with a background-image that keeps the aspect ratio of the image, with a fixed height of 500px and i want no "padding" on the background of that div.
Is this possible to do?

I Can get a div with a fixed height and a background-image that keeps aspect ratio :

<div style="background: url(something.png) 50% 50% / cover #D6D6D6;background-size: contain;background-repeat: no-repeat;height:500px"></div>

This makes the image centered in the middle of the div ( either vertically or horizontally ) but gives some padding to the background of the div ...

Can anybody help me out ?


What you are trying to achieve is not possible using only CSS, you could use JavaScript to detect the width of the image and then set the width of the div to be the same. Or alternatively you could simply remove the background-image property and rather add the image as an img tag into your HTML. If you do that you can display the div as inline-block which will take care of making the div as wide as the width of the image.

div img
  <img src="http://lorempixel.com/200/500" alt="">