How to keep image aspect ratio inside resizable div?

Viewed 32

I have an image inside a resizable div like this:

jsfiddle

#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%);
    
    width:70%;

}
<div id="img_wrapper">
  <img src="https://i.ibb.co/zJvjmKs/icon.png" id="img_testing">
</div>

I'm trying to keep the aspect ratio of the image to whichever size the div is resized

for example:

This is correct
enter image description here

This is incorrect
enter image description here

Whereas it should look like this:
enter image description here

1 Answers

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