Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an image fit inside a div element when the image is wider than the div?

Tags:

html

I've an image tag inside a div element.

<div id = "myDiv">
 <img alt = "myImage" src = "some_source"/>
</div>

The image is bigger than the div, so the image is not inside the div element. First, I've thought about using width = x, height = y. But as I'm still designing the page, I fear to have to worry all the time those 2 dimensions.

How can I keep the image inside the div element? also, respecting the dimensions of the div element?

Thanks for helping

like image 293
Richard77 Avatar asked Sep 06 '10 10:09

Richard77


People also ask

How do I force an image to fit in a div?

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.

How do I make a picture fit a div without stretching it?

How to fit image without stretching and maintain aspect ratio? Answer: If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property. contain will give you a scaled-down image.


Video Answer


1 Answers

Guys after spending too much time looking around for an easier way to do this, I combine the info from research to do it like this: (simply using the getimagesize() function -if the height is larger than the width, echo an image tag with a style having a height of 100% else echo the same image tag but with a style having a width of 100%);

$image = "path to your image";
$img_size = getimagesize($image);

if ($img_size[0] < $img_size[1]){echo " < img src= '$image'  style='height:100%;'>";}
else {echo "< img src= '$image'  style='width:100%;'>";}
like image 188
Nicholas Avatar answered Nov 02 '22 14:11

Nicholas