Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't object-fit affect width or height?

Tags:

html

css

flexbox

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).

enter image description here

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>
like image 591
alexandernst Avatar asked Apr 15 '16 01:04

alexandernst


People also ask

Why does object-fit not work?

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.

What will happen if width and height of the image is not specified?

If width and height are not specified, the page will flicker while the image loads.

Which element height and width can not be set?

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.


1 Answers

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.

like image 142
Stickers Avatar answered Nov 11 '22 05:11

Stickers