I have a 240*240px image inside a 100*300px div (demo values, actual values vary and are unknown). I use object-fit: contain
to make the image completely visible inside the div and also keep it's aspect ratio. The problem is that object-fit
isn't modifying the width of the image, resulting in a weird "padding" (so to say).
How can I make the image take only as much width as required, instead of taking the original width?
Demo: http://codepen.io/alexandernst/pen/ONvqzN
.wrapper {
height: 100px;
width: 300px;
border: 1px solid black;
}
.flex {
display: flex;
}
img {
object-fit: contain;
}
<div class="flex wrapper">
<img src="https://unsplash.it/240/240" />
</div>
For object-fit to work, the image itself needs a width and height . In the OP's CSS, the images do not have width and/or height set, thus object-fit cannot work.
If width and height are not specified, the page will flicker while the image loads.
inline The element doesn't start on a new line and only occupy just the width it requires. You can't set the width or height. inline-block It's formatted just like the inline element, where it doesn't start on a new line.
The object-fit
property normally works together with width
, height
, max-width
and max-height
. Example:
.wrapper {
height: 100px;
width: 300px;
border: 1px solid black;
}
.flex {
display: flex;
}
img {
object-fit: contain;
height: 100%;
width: auto;
}
<div class="flex wrapper">
<img src="https://unsplash.it/240/240" />
</div>
In fact, it works fine too even without object-fit
, see this jsFiddle.
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