Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image max height 100% inside flexbox

Tags:

html

css

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>
like image 458
Uday Hiwarale Avatar asked Oct 22 '25 13:10

Uday Hiwarale


1 Answers

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/

like image 104
Godwin Avatar answered Oct 24 '25 04:10

Godwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!