Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I auto-resize an image to fit a 'div' container?

How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining its width:height ratio?


Example: stackoverflow.com - when an image is inserted onto the editor panel and the image is too large to fit onto the page, the image is automatically resized.

like image 625
001 Avatar asked Jun 12 '10 17:06

001


People also ask

How do I make an image fit into a container?

The CSS object-fit property is used to specify how an <img> or <video> should be resized to fit its container. This property tells the content to fill the container in a variety of ways; such as "preserve that aspect ratio" or "stretch up and take up as much space as possible".

How do you auto fit an image in HTML?

The max-height property sets the maximum height of an element, and the max-width property sets the maximum width of an element. 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.

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.


2 Answers

Do not apply an explicit width or height to the image tag. Instead, give it:

max-width:100%; max-height:100%; 

Also, height: auto; if you want to specify a width only.

Example: http://jsfiddle.net/xwrvxser/1/

img {      max-width: 100%;      max-height: 100%;  }    .portrait {      height: 80px;      width: 30px;  }    .landscape {      height: 30px;      width: 80px;  }    .square {      height: 75px;      width: 75px;  }
Portrait Div  <div class="portrait">      <img src="http://i.stack.imgur.com/xkF9Q.jpg">  </div>    Landscape Div  <div class="landscape">      <img src="http://i.stack.imgur.com/xkF9Q.jpg">  </div>    Square Div  <div class="square">      <img src="http://i.stack.imgur.com/xkF9Q.jpg">  </div>
like image 166
Kevin Avatar answered Sep 20 '22 10:09

Kevin


object-fit

It turns out there's another way to do this.

<img style='height: 100%; width: 100%; object-fit: contain'/> 

will do the work. It's CSS 3 stuff.

Fiddle: http://jsfiddle.net/mbHB4/7364/

like image 41
Shih-Min Lee Avatar answered Sep 20 '22 10:09

Shih-Min Lee