Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 489
JohnIdol Avatar asked Mar 01 '09 23:03

JohnIdol


People also ask

How auto adjust height in div?

If height: auto; the element will automatically adjust its height to allow its content to be displayed correctly. If height is set to a numeric value (like pixels, (r)em, percentages) then if the content does not fit within the specified height, it will overflow.

How do I automatically resize a background image?

There are four different syntaxes you can use with this property: the keyword syntax ("auto", "cover" and "contain"), the one-value syntax (sets the width of the image (height becomes "auto"), the two-value syntax (first value: width of the image, second value: height), and the multiple background syntax (separated ...

How do I resize a div to fit an image?

To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.


1 Answers

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/

like image 61
Hasanavi Avatar answered Sep 18 '22 06:09

Hasanavi