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.
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.
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.
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).
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With