0

I needed an image to fill a div. As per this answer, the job was almost done. The problem arises when the images are somewhat larger than the div they are contained in. The images are shown at 100% scale, which in my case isn't ideal.

In Firefox the problem can be solved by using this CSS instead:

.fill img {
  min-height: 100%;
}

In other browsers (tested with Chrome and Edge) this solution doesn't work and the end result is the same as before.

Is there a way to achieve the same result as in Firefox across other browsers?

Here is a fiddle with a mockup layout, demonstrating this behaviour: https://jsfiddle.net/jqe5gfru/4/

.container {
  border: 2px solid red;
  width: 300px;
  height: 40vh;
  margin: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.item {
  min-height: 100%;
}
<div class="container">
  <img class="item" src="http://placekitten.com/1600/400" />
</div>

<div class="container">
  <img class="item" src="http://placekitten.com/600/1200" />
</div>

Try opening it in Firefox and some other browser and compare the result.

yunzen
  • 32,854
  • 11
  • 73
  • 106

1 Answers1

2

You could try using object-fit:cover for the supporting browsers

.container {
  border: 2px solid red;
  width: 300px;
  height: 40vh;
  margin: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.item {
  height: 100%;
  width: 100%;
  object-fit: cover;
}
<div class="container">
  <img class="item" src="http://placekitten.com/1600/400" />
</div>

<div class="container">
  <img class="item" src="http://placekitten.com/600/1200" />
</div>
yunzen
  • 32,854
  • 11
  • 73
  • 106
  • Thanks, this seems to do the trick! The only caveat is if I wanted to use `align-items: flex-start | flex-end`. In this case `object-fit: cover` overrides it and vertically centers the containing image. Is there a way around this? – Tjaz Brelih Jul 09 '19 at 10:57
  • 1
    You can use `object-position` on `.item`. Use `50% 0%` to simulate `align-items: flex-start` and `50% 100%` for `flex-end` – yunzen Jul 09 '19 at 11:13