How to get div height to auto-adjust to background size?
There is a very nice and cool way to make a background image work like an img
element so it adjust its height
automatically. You need to know the image width
and height
ratio. Set the height
of the container to 0 and set the padding-top
as percentage based upon the image ratio.
It will look like the following:
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: contain;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 66.64%; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
You just got a background image with auto height which will work just like an img element. Here is a working prototype (you can resize and check the div height): http://jsfiddle.net/8m9ur5qj/
Another, perhaps inefficient, solution would be to include the image under an img
element set to visibility: hidden;
. Then make the background-image
of the surrounding div the same as the image.
This will set the surrounding div to the size of the image in the img
element but display it as a background.
<div style="background-image: url(http://your-image.jpg);">
<img src="http://your-image.jpg" style="visibility: hidden;" />
</div>