How do I fit an image (img) inside a div and keep the aspect ratio?
Using CSS only:
div > img {
width: auto;
height : auto;
max-height: 100%;
max-width: 100%;
}
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="" />
</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.
Use max-height:100%; max-width:100%;
for the image inside the div.
CSS Object-fit
Unfortunately max-width + max-height do not fully cover my task... So I have found another solution:
To save the Image ratio while scaling you also can use object-fit
CSS3 propperty.
Useful article: Control image aspect ratios with CSS3
img {
width: 100%; /* or any custom size */
height: 100%;
object-fit: contain;
}
Bad news: IE not supported (Can I Use)