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

I have a 48x48 div and inside it there is an img element, I want to fit it into the div without losing any part, in the mean time the ratio is kept, is it achievable using html and css?

This question is related to html css

The answer is


Setting the photo as a background image will give us more control over size and placement, leaving the img tag to serve a different purpose...

Below, if we want the div to be the same aspect ratio as the photo, then placeholder.png is a small transparent image with the same aspect ratio as photo.jpg. If the photo is a square, it's a 1px x 1px placeholder, if the photo is a video thumbnail, it's a 16x9 placeholder, etc.

Specific to the question, use a 1x1 placeholder to maintain the div's square ratio, with a background image using background-size to maintain the photo's aspect ratio.

I used background-position: center center; so the photo will be centered in the div. (Aligning the photo in the vertical center or bottom would get ugly with the photo in the img tag.)

div {
    background: url(photo.jpg) center center no-repeat;
    background-size: contain;
    width: 48px; // or a % in responsive layout
}
img {
    width: 100%;
}

<div><img src="placeholder.png"/></div>

To avoid an extra http request, convert the placeholder image to a data: URL.

<img src="data:image/png;base64,..."/>

Using CSS only:

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

Try CSS:

img {
  object-fit: cover;
  height: 48px;
}

Here's an all JavaScript approach. It scales an image incrementally down until it fits correctly. You choose how much to shrink it each time it fails. This example shrinks it 10% each time it fails:

let fit = function (el, w, h, percentage, step)
{
    let newH = h;
    let newW = w;

    // fail safe
    if (percentage < 0 || step < 0) return { h: h, w: w };
    if (h > w)
    {
        newH = el.height() * percentage;
        newW = (w / h) * newH;
        if (newW > el.width())
        {
            return fit(el, w, h, percentage - step, step);
        }
    }
    else
    {
        newW = el.width() * percentage;
        newH = (h / w) * newW;
        if (newH > el.height())
        {
            return fit(el, w, h, percentage - step, step);
        }
    }

    return { h: newH, w: newW };
};

img.bind('load', function ()
{
    let h = img.height();
    let w = img.width();
    let newFit = fit($('<img-wrapper-selector>'), w, h, 1, 0.1);

    img.width(newFit.w);
    img.height(newFit.h);
});

Feel free to copy and paste directly.


What worked for me was:

<div style='display: inline-flex; width: 80px; height: 80px;'>
<img style='max-width: 100%; max-height: 100%' src='image file'>
</div>

inline-flex was required to keep the images from going outside of the div.


For me, the following CSS worked (tested in Chrome, Firefox and Safari).

There are multiple things working together:

  • max-height: 100%;, max-width: 100%; and height: auto;, width: auto; make the img scale to whichever dimension first reaches 100% while keeping the aspect ratio
  • position: relative; in the container and position: absolute; in the child together with top: 50%; and left: 50%; center the top left corner of the img in the container
  • transform: translate(-50%, -50%); moves the img back to the left and top by half its size, thus centering the img in the container

CSS:

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

    position: relative;
}

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

    position: absolute;
    top: 50%;
    left: 50%;

    transform: translate(-50%, -50%);
}

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)


I was having a lot of problems to get this working, every single solution I found didn't seem to work.

I realized that I had to set the div display to flex, so basically this is my CSS:

div{
display: flex;
}

div img{ 
max-height: 100%;
max-width: 100%;
}

HTML

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

CSS

div {
   width: 48px;
   height: 48px;
}

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

This will make the image expand to fill its parent, of which its size is set in the div CSS.


you can use class "img-fluid" for newer version i.e Bootstrap v4.

and can use class "img-responsive" for older version like Bootstrap v3.

Usage:-

img tag with :-

class="img-fluid"

src="..."


Use max-height:100%; max-width:100%; for the image inside the div.