Home > Back-end >  How to keep image aspect ratio inside resizable div?
How to keep image aspect ratio inside resizable div?

Time:05-20

I have an image inside a resizable div like this:

enter image description here

This is incorrect
enter image description here

Whereas it should look like this:
enter image description here

CodePudding user response:

You could use max height and width values, then force the proportions of the image using the object-fit attribute

#img_wrapper {
  resize: both;
  overflow: hidden;
  background-color: gray;
  height: 15rem;
  width: 15rem;
  min-height: 15rem;
  min-width: 15rem;
  user-select: none;
}

#img_testing {
  display: block;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: auto;
  width: 70%;
  max-width: 70%;
  max-height: 70%;
  object-fit: contain;
}
<div id="img_wrapper">
  <img src="https://i.ibb.co/zJvjmKs/icon.png" id="img_testing">
</div>

  • Related