Uday Hiwarale Uday Hiwarale - 4 months ago 79
HTML Question

Image max height 100% inside flexbox

I am getting a glitch when setting max-height and max-width of an image inside a flex container.

Following is the css for flex container

.galleria-images{
display: flex;
flex-direction: row;
justify-content: center;
align-items:center;
flex : 1; /* It's also a flex item hence take default height available in viewport */
}


Now my application is to have a child image to flex container which is centred on both axis. But it should not exceed height or width of a parent container (flex container). I also don't want image to shrink or grow to maintain aspect ratio. Hence I wrote following css.

img{
flex:0 0 auto;
vertical-align: bottom;
max-width: 100%;
max-height: 100%;
}


But this is now working out for me. Even though flex container has flexible height, image inside it is overflowing.

enter image description here

This works when the viewport orientation is changed. As shown below.

enter image description here

Anything else that can be done???

JSfiddle



.galleria {
position: absolute;
top: 0;
bottom: 0;
left: 80px;
right: 80px;
background-color: rgba(100, 100, 100, 0.5);
overflow: hidden;
display: flex;
flex-direction: column;
}
.galleria .galleria-images {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
flex: 1;
background-color: rgba(200, 200, 200, 0.7);
}
.galleria .galleria-images img {
flex: 0 0 auto;
vertical-align: bottom;
max-width: 100%;
max-height: 100%;
}
.galleria .galleria-thumbs {
flex: 0 0 50px;
background-color: rgba(200, 200, 200, 0.3);
}

<div class="galleria">
<div class="galleria-images">
<img src="https://pixabay.com/static/uploads/photo/2016/06/13/07/32/cactus-1453793_960_720.jpg">
</div>
<div class="galleria-thumbs">
</div>
</div>




Answer

The image element is ignoring its direct parent because it has a static position. Try making the parent element relatively positioned and make the image absolutely positioned:

.galleria-images {
    position: relative;
}

.galleria-images img {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

Updated fiddle: https://jsfiddle.net/o4w7t61u/