Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is object-fit not working with max-height container?

Tags:

css

height

I'm trying to place a video into a container which has 100% width and auto height respecting the aspect ratio but with max-height set. I want the video to fill the entire container even if the sides are cropped and to be centered both horizontally and vertically.

I'm using fit-object property but apparently it doesn't work with max-height.

I'll simplify it with an image. The result should be the same.

HTML

<div>
    <img src="...">
</div>

CSS

div {
    width: 100%;
    overflow: hidden;
}
img {
    object-fit: cover;
    width: 100%;
    height: 100%;
}

Now, if I add to div style height: 100px, it works. If I write max-height: 100px, it doesn't. Is this expected behaviour? If so, what can I do to make it work?

Here is jsFiddle: http://jsfiddle.net/1r4mLvLq/

like image 693
samuelg0rd0n Avatar asked Aug 11 '15 15:08

samuelg0rd0n


People also ask

Why object-fit property is not working?

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.

How do I force an image to fit in a div?

To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.

How does object-fit works?

The object-fit CSS property sets how the content of a replaced element, such as an <img> or <video> , should be resized to fit its container. You can alter the alignment of the replaced element's content object within the element's box using the object-position property.


1 Answers

height: 100%; works only if an ancestor element has an explicit height set.

You can accomplish that by adding this CSS:

html, body {
  height: 100%;
  margin: 0;
}

Updated Fiddle

like image 195
Rick Hitchcock Avatar answered Nov 09 '22 02:11

Rick Hitchcock