skip to Main Content

I have a div with a max-height. It contains an image with a portrait aspect ratio. My goal is, that the image should adapt to the size of the container (getting max its height and max. it’s width), without losing it’s aspect ratio.

When I use height: auto; width: 100% on the image, the image gets larger than its parents max-height.

On the other hand, if I set width: auto; height: 100% on the image, it can get larger than its parents width.

And if I set max-height: 50px; width: 100%; it can get distorted, depending on its parents width.

.container {
  max-height: 50px;
  border: 2px solid red;
}

img {
  width: 100%;
  height: auto
}
<div class="container">
  <img src="https://placehold.co/40x60.jpg" width="40" height="60"/>
</div>

2

Answers


  1. Maybe with CSS grid

    .container {
      max-height: 50px;
      border: 2px solid red;
      display: grid;
      place-content: center;
      grid-template-rows: 100%;
      
      /* for the demo */
      overflow: hidden;
      resize: auto;
    }
    
    img {
      max-height: 100%;
      max-width: 100%;
      height: auto;
      width: auto;
      margin: auto;
    }
    <div class="container">
      <img src="https://placehold.co/40x60.jpg" width="40" height="60" >
    </div>
    Login or Signup to reply.
  2. May be we can reduce code of css

    .container
    {
      max-height: 50px;
      border: 2px solid red;
      display: grid;
      grid-template-rows: 100%;
      overflow: hidden;
      resize: auto;
    }
    
    .container img
    {
      max-height: 100%;
      max-width: 100%;
      margin: auto;
    }
    <div class="container">
     <img src="https://placehold.co/40x60.jpg" >
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search