I have a div of dimensions 630x630px. Now I want to place an image inside this div. If image is larger than 630px (it’s width or height) I can simply use max-width and max-height and it will be fitted to 630px. But what if image is smaller than 630px? In that case I would like this image’s larger dimension to be stretched with constant aspect ratio to 630px. How can I do it?
>Solution :
You can use the object-fit and object-position CSS properties on the image to achieve this. Your code should look like this:
.container {
width: 630px;
height: 630px;
position: relative;
}
.container img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
object-fit: contain;
object-position: center center;
}