How to Fit an Image (Img) Inside a Div and Keep the Aspect Ratio

How do I fit an image (img) inside a div and keep the aspect ratio?

You will need some JavaScript to prevent cropping if you don't know the dimension of the image at the time you're writing the css.

HTML & JavaScript

<div id="container">
<img src="something.jpg" alt="Sample Image" />
</div>

<script type="text/javascript">
(function() {

var img = document.getElementById('container').firstChild;
img.onload = function() {
if(img.height > img.width) {
img.height = '100%';
img.width = 'auto';
}
};

}());
</script>

CSS

#container {
width: 48px;
height: 48px;
}

#container img {
width: 100%;
}

If you use a JavaScript Library you might want to take advantage of it.

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

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>

In css, how to maximize an image's size within a div while keep its aspect-ratio?

As mentioned in the comments, using object-fit: contain will achieve your desired result. Here is a 200x200px image being contained within a 150x100px div:

.container {
width: 150px;
height: 100px;
border: 1px solid red;
}

img {
width: 100%;
height: 100%;
object-fit: contain;
}
<div class="container">
<img src="https://via.placeholder.com/200x200.jpg"/>
</div>

How do you stretch an image to fill a div while keeping the image's aspect-ratio?

Update 2019.

You can now use the object-fit css property that accepts the following values: fill | contain | cover | none | scale-down

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

As an example, you could have a container that holds an image:

<div class="container">
<img src="" class="container_img" />
</div>

.container {
height: 50px;
width: 50%;
}

.container_img {
height: 100%;
width: 100%;
object-fit: cover;
}

CSS force image resize and keep aspect ratio