Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change DIV height to fit image

Tags:

html

css

I'm trying to make a DIV that's pretty much a box with a border that has a left-aligned image and text that's to the right of the image. Here's how I have it set up:

    <div style="padding:1%; border-style:solid; border-size:1px; width:100%;">
        <img src="http://i.imgur.com/FwgZFNn.jpg" style="float:left; max-width:30%; max-height:200px;" />
        Here is some text.
    </div>

The problem is that, if the image is taller than the text, the surrounding DIV (and therefore the border) sizes itself to become the height it needs to be to fit in all the text, but the image overflows out of the DIV.

How can I make the DIV change its height to fit whichever is taller (the image or the text) so that both fit within the border?

Thanks.

like image 967
Leon Overweel Avatar asked Nov 13 '14 14:11

Leon Overweel


People also ask

How to fit an image in a Div using CSS?

To fit an image in a div, use the css object-fit property. <div> <img src="abidjan.jpg" alt="Abidjan" width="400" height="300"> <div> NB : Note the width and height attributes of the img. img { width: 200px; height: 300px; object-fit: fill; /* You can also use cover instead of fill but they are different */ }

How to calculate the height of a Div using image ratio?

When we have image ratio we can simply calculate the height of the div by multiplying the ratio by viewport width: To me, it works, sets div height properly and changes it when the window is resized.

How do I change the size of an image in CSS?

To resize an image proportionally, set either the height or width to "100%", but not both. If you set both to "100%", the image will be stretched. To use an image as a CSS background, use the background-size property. This property offers two special values: contain and cover.

How to adjust the height of a background image automatically?

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.


1 Answers

Just before the end of the div i.e before </div>, you need to clear the float. The error is due to float style of the image. To clear the float just add this

<span style="clear:both;"></span>

Just before the </div> tag.

like image 121
monk Avatar answered Oct 10 '22 09:10

monk