Home > Enterprise >  How to keep image to fill container, keep pixel-aspect-ratio and have two bounds aligned with contai
How to keep image to fill container, keep pixel-aspect-ratio and have two bounds aligned with contai

Time:03-09

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

CodePudding user response:

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 >
        <img src="https://ichef.bbci.co.uk/news/976/cpsprodpb/12A9B/production/_111434467_gettyimages-1143489763.jpg">
    </div>


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

CodePudding user response:

Yes, just use percentage in place of pixel for width and VH in place of pixel for height.

For Example

img{

width:100%;
height: 100vh;

}

  • Related