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?
2
Answers
You can use the
object-fit
andobject-position
CSS properties on the image to achieve this. Your code should look like this:I would avoid using
position: absolute;
when it’s unnecessary.object-fit
does the trick by itself.