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

HtmlCss

Html Problem Overview


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?

Html Solutions


Solution 1 - Html

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

Solution 2 - Html

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)

Solution 3 - Html

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.

Solution 4 - Html

Using CSS only:

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

Solution 5 - Html

###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.

Solution 6 - Html

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%;
}

Solution 7 - Html

Try CSS:

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

Solution 8 - Html

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%);
}

Solution 9 - Html

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,..."/>

Solution 10 - Html

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="..."

Solution 11 - Html

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.

Solution 12 - Html

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.

Solution 13 - Html

Super late but, try this solution:

.parent {
  display: flex;
  min-height: 400px; /* if you prefer */
}

.parent > img {
  display: block;
  width: 100%;
  max-width: 100%;
  object-fit: cover;
}
  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBin ChenView Question on Stackoverflow
Solution 1 - HtmlMichaelView Answer on Stackoverflow
Solution 2 - HtmlAndrii VerbytskyiView Answer on Stackoverflow
Solution 3 - HtmlThomasView Answer on Stackoverflow
Solution 4 - HtmlMaxView Answer on Stackoverflow
Solution 5 - HtmlalexView Answer on Stackoverflow
Solution 6 - HtmlBartho BernsmannView Answer on Stackoverflow
Solution 7 - HtmlFaisalView Answer on Stackoverflow
Solution 8 - HtmlVSchlattingerView Answer on Stackoverflow
Solution 9 - HtmlWebveloperView Answer on Stackoverflow
Solution 10 - HtmlSaurabh SheorainView Answer on Stackoverflow
Solution 11 - HtmlNomad77View Answer on Stackoverflow
Solution 12 - HtmlJared BeachView Answer on Stackoverflow
Solution 13 - HtmlPratikno RuliantoView Answer on Stackoverflow