Search code examples
htmlcss

Displaying an image without cropping or stretching etc with max-height


I have an image (of which I don't precisely know the width / height --> loaded from database), which should stretch to the full container-width (see rounded corners). This I solved quite nicely. But especially with portrait images, they sometimes get too large, therefore I would like to apply a max-height. How can I do this?

Current code without a max-height (works great otherwise)

.avatar-box {
  position: relative;
  overflow: hidden;
  border-radius: 10px;
}

.avatar-thumb-square2 {
  overflow: hidden;
  position: relative;
}

.avatar-thumb-square2 .avatar-image {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 100%;
}
<div class="avatar-box" data-controller="responsive-image">
  <div class="avatar-thumb-square2">
    <img class="avatar-image" src="https://www.alten.com/wp-content/uploads/2021/05/satellite-donnees-oceanographiques.jpg">
  </div>
</div>

This results in something like this: enter image description here

But as you can see, the image is too large vertically, therefore I would like to apply a max-height. How can I limit the image size to grow to a max of 400px for example. By just applying a max-height, the image gets cropped. See sample

enter image description here

So how can I show the full image (center it if it doesn't stretch 100%) and keep the rounded corners? I'm okay to use JavaScript.


Solution

  • .avatar-thumb-square2 .avatar-image {
        width: 100%;
        object-fit: cover;
        height: 300px;
        border-radius: 10px;
    }
    
    .avatar-thumb-square2{
        width:30%;
    }
    <div class="avatar-box" data-controller="responsive-image">
      <div class="avatar-thumb-square2" data-responsive-image-target="wrapper">
        <img class="avatar-image" src="https://www.alten.com/wp-content/uploads/2021/05/satellite-donnees-oceanographiques.jpg">
      </div>
    </div>