Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image with object-fit not filling container

I have a banner image that's wider than it is tall. I have a container div that displays different sizes of images, and for the banner style, I need it to stretch and/or squash to fill the parent div in both directions. I've looked at object-fit:fill, but it only seems to stretch the image horizontally - it doesn't do anything about making it fill the div vertically.

A working example is here; code looks like this:

.tile {
  position: relative;
  float: left;
  margin: 10px;
  border: 4px solid green;
  height: 400px;
}

.deal {
  width: 342px;
  background: #ffffff;
}

.tileImage.promo {
  object-fit: fill;
}
<div class="tile deal hsNational active">
  <img class="tileImage promo" src="https://cdn.pixabay.com/photo/2015/12/13/09/42/banner-1090835_960_720.jpg" height="200px">
</div>

What am I doing wrong? (I've tried the various values for object-fit, and none of them do what I need.) The image should be squished horizontally and stretched vertically to completely fill the area inside the green border.

like image 801
EmmyS Avatar asked Sep 21 '17 21:09

EmmyS


People also ask

How do I make a picture fit a container size?

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.

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.

What can I use instead of object-fit?

Instead of object-fit / object-position embed the image to the background by using background-size / background-position. Alternatively, you can play with the transform property and with absolute positioning (See StackOverflow).


1 Answers

Define dimensions for the image, then object-fit works:

.tile {
    position: relative;
    float: left;
    margin: 10px;
    border: 4px solid green;
    height: 400px;
}

.deal {
    width: 342px;
    background: #ffffff;
}

.tileImage.promo {
    object-fit: fill; /* also try 'contain' and 'cover' */
    width: 100%;
    height: 100%;
}
<div class="tile deal hsNational active">
  <img class="tileImage promo" src="https://cdn.pixabay.com/photo/2015/12/13/09/42/banner-1090835_960_720.jpg">
</div>

More details here: Why isn't object-fit working in flexbox?

like image 82
Michael Benjamin Avatar answered Oct 01 '22 19:10

Michael Benjamin