Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox stretching an element centered with Flexbox

I'm trying to center an element (im my case an image) with arbitrary size inside a box. Everything works fine in Webkit browsers, but Firefox stretches images that are longer than they are wide.

To illustrate the problem, I create 3 div as boxes, each of containing a differently sized image. The boxes are all set to a fixed width and height, and a couple of flexbox rules are applied to center the image both vertically and horizontally.

* {
  box-sizing: border-box;
}

.box {
  display: flex;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  justify-content: center;
  align-items: center;
  float: left;
  margin-right: 50px;
}

.box img {
  max-width: 100%;
  max-height: 100%;
}
<div class="box">
  <img src="http://dummyimage.com/150x150/eeeeee.png">
</div>
<div class="box">
  <img src="http://dummyimage.com/300x150/eeeeee.png">
</div>
<div class="box">
  <img src="http://dummyimage.com/150x300/eeeeee.png">
</div>

The img should be shrunk such that they exactly fill the box (either horizontally or vertically, which ever side is longer), but preserving the aspect ratio. This is exactly what happens in Webkit browsers. However, Firefox just stretches the one image that is longer than high in vertical direction. How can I make Firefox behave the same way as all the Webkit browsers?

like image 934
m4r73n Avatar asked Feb 09 '23 23:02

m4r73n


1 Answers

Using "object-fit: contain" for the images seems to do the trick :)

.box img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

http://jsfiddle.net/xjwguxs6/

like image 104
cssmaniac Avatar answered Feb 11 '23 14:02

cssmaniac