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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With