7

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.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
EmmyS
  • 11,892
  • 48
  • 101
  • 156

1 Answers1

6

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?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 1
    Thank you; that's what I needed. I'm a backend developer, so my CSS isn't super-strong, and the example I saw didn't have any mention of needing to set default sizes on the image. – EmmyS Sep 21 '17 at 22:08
  • What do I do if I need multiple images in the DIV? I can't define *both* height and width to 100%, otherwise the first image takes up all available space and covers up the remaining images. But if I don't define width, or define it as "auto", then nothing happens. – Michael Sep 08 '20 at 00:54
  • OMFG THANK YOU - I've been up all night wrangling with this – bhu Boue vidya Oct 20 '21 at 18:35