0

I have an image which I want to display undistorted (it should scale, but not get distorted). However, when the container has a greater width-to-height aspect ratio than the image, then I want the left and right border of the image be aligned with the container and the top and bottom of the image be cropped, and when the aspect ratio is smaller than that of the image, then I want the top and bottom to be aligned with the top and bottom of the container and the left and right side of the image be cropped. So the image should always fill the container and be cropped and centered depending on container aspect ratio.

like this (red showing the aspect ratio of the container) keeping image to fill container

How can I do that with CSS?

I did try

.fill {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden
}
.fill img {
    flex-shrink: 0;
    min-width: 100%;
    min-height: 100%
}

from How can I fill a div with an image while keeping it proportional? but this just sticks the image into the top left corner of my window

matthias_buehlmann
  • 4,641
  • 6
  • 34
  • 76

1 Answers1

0

Solution 1

CSS The object-fit Property

The CSS object-fit property is used to specify how an or should be resized to fit its container.

.img-outer {
            width: 200px;
            height: 200px;
            overflow: hidden;
            background: #000;
            display: flex;
            align-items: center;
            justify-content: center;
margin-bottom: 18px !important;
        }

        .img-outer img {
            object-fit: cover;
            max-width: calc(100% + 50px);
            min-height: 100%;
            min-width: calc(100% + 50px);
            max-height: calc(100% + 50px);
            width: auto;
            height: auto;
        }
<div class="img-outer">
        <img src="https://ichef.bbci.co.uk/news/976/cpsprodpb/12A9B/production/_111434467_gettyimages-1143489763.jpg">
    </div>


 <div class="img-outer">
        <img src="https://images.unsplash.com/photo-1560115246-30778a6578be?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8Y3V0ZSUyMGNhdHxlbnwwfHwwfHw%3D&w=1000&q=80">
    </div>

Solution 2 This should do it:

img {    
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
}
Priya jain
  • 1,127
  • 2
  • 10
  • 22
  • can you please explain `margin-bottom: 18px !important;` and your values of `min-width` `max-width` and `min-height` and `max-height`? I want the image to always cover the div with either side edges or top-bottom exges aligned with the div (so the image should bot scale up as well as scale down if the div is larger or smaller than the image) – matthias_buehlmann Mar 08 '22 at 14:05