Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scratch image to fill div with aspect ratio or limit dimensions if image is bigger than div

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading