Coder Perfect

How do I retain the aspect ratio of an image (img) while fitting it into a div?


I have a 48×48 div with an img element inside it; I want to fit it into the div without losing any part of it while maintaining the ratio; is this possible with html and CSS?

Asked by Bin Chen

Solution #1

For the image inside the div, use max-height:100%; max-width:100%.

Answered by Michael

Solution #2

Unfortunately, max-width + max-height are insufficient for my needs… As a result, I’ve devised a new strategy:

You may also use the object-fit CSS3 property to keep the image ratio while scaling.

Control picture aspect ratios using CSS3 is a useful article.

img {
    width: 100%; /* or any custom size */
    height: 100%; 
    object-fit: contain;

The bad news is that Internet Explorer isn’t supported (Can I Use)

Answered by Andrii Verbytskyi

Solution #3

If you don’t know the image’s dimensions when you’re writing the CSS, you’ll need some JavaScript to prevent cropping.

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

<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';

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

#container img {
   width: 100%;

You might want to take advantage of a JavaScript Library if you utilize one.

Answered by Thomas

Solution #4

Using CSS only:

div > img {
  width: auto;
  height : auto;
  max-height: 100%;
  max-width: 100%;

Answered by Max

Solution #5

    <img src="something.jpg" alt="" />
div {
   width: 48px;
   height: 48px;

div img {
   display: block;
   width: 100%;

This causes the image to grow to fill its parent, whose size is determined by the div CSS.

Answered by alex

Post is based on