Search code examples
htmlcssobject-fit

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.


Solution

  • 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?