htmlimage

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?


I need to make this image stretch to the maximum size possible without overflowing it's <div> or skewing the image.

I can't predict the aspect-ratio of the image, so there's no way to know whether to use:

<img src="url" style="width: 100%;">

or

<img src="url" style="height: 100%;">

I can't use both (i.e. style="width: 100%; height: 100%;") because that will stretch the image to fit the <div>.

The <div> has a size set by percentage of the screen, which is also unpredictable.


Solution

  • If you're able to set the image as a background-image then you can do something like this, which will crop the image without stretching it:

    <div style="background-image: url(...); background-size: cover; width: 100%; height: 100%;"></div>
    

    If you need to stick with an <img> tag, then as of 2019, you can now use the object-fit css property that accepts the following values:
    fill | contain | cover | none | scale-down

    See https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

    As an example, you could have a container that holds an image:

    <div class="container">
        <img src="" class="container_img" />
    </div>
    
    .container {
        height: 50px;
        width: 50%;
    }
    
    .container_img {
        height: 100%;
        width: 100%;
        object-fit: cover;
    }