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

PHOTO EMBED

Thu Jul 14 2022 10:41:35 GMT+0000 (UTC)

Saved by @oday #html

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

#container img {
   width: 100%;
}


-----------------------------------------------JS-------------------------------------------



<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>
content_copyCOPY

https://stackoverflow.com/questions/4394309/how-do-i-fit-an-image-img-inside-a-div-and-keep-the-aspect-ratio