How to get div height to auto-adjust to background size?

JohnIdol picture JohnIdol · Mar 2, 2009 · Viewed 469.7k times · Source

How do I get a div to automatically adjust to the size of the background I set for it without setting a specific height (or min-height) for it?

Answer

Hasanavi picture Hasanavi · Mar 6, 2014

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/TPEFn/2/