htmlcssflexboxstretch

Image inside flex parent with max-height and max-width and object-fit contain


Image stretches if I don't use object-fit contains. Stretches in width, losing aspect ratio.

object-fit contain fixes that.

The problem is, the element itself is not contained, just the visible image. Which means if I make the image clickable, the whole element area (even outside the image) is clickable.

https://jsfiddle.net/nyysyngp/10/ (or see code below)

I just want the visible image to be clickable. This seems to work on Firefox, but not Chrome.

body, html
{
  margin: 0;
  padding: 0;
  background-color: red;
  display: flex;
  height: 100%;
  width: 100%;
}

#media
{
    display: flex;
    background-color: #262423;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    flex-grow: 1;  
}

#media_split 
{
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    align-items: center;
}

#media_image_container 
{
    height: 50%;
    width: 100%;
    flex-grow: 1;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: green;
}

#media_image 
{
    object-fit: contain;
    max-height: calc(100% - 4em);
    max-width: calc(100% - 4.7em);
    min-height: 100px;
    min-width: 100px;
    cursor: pointer;
}

#media_tv 
{
    height: 50%;
    width: 100%;
    flex-grow: 1;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color:blue;
}
<div id='media'>

  <div id='media_split'>
  
    <div id='media_image_container'>
      <img id='media_image' src='https://i.imgur.com/F26h0tq.jpg'>
    </div>
    
    <div id='media_tv'></div>
    
  </div>
  
</div>


Solution

  • Well some months later I found a solution. Just by adding "position: absolute" to #media_image the problem went away, which in my case didn't break anything else.