0

I'm trying to figure out how to use object-fit to properly scale a 16:9 vertical image.

I've tried almost anything with no luck!

https://jsfiddle.net/pdocys3j/

.container {
  width: 300px; /*any size*/
  height: 200px; /*any size*/
}

.object-fit-cover {
  width: 100%;
  height: 100%;
  object-fit: cover; /*magic*/
}
<div class="container">
  <img class="object-fit-cover" src="https://jardim-plant-images-development.s3.amazonaws.com/hfj1h9jq2q8o8tyv1r6dxhi4zrmn">
</div>

The expected result (without using object-fit:

.container {
  width: 300px; /*any size*/
  height: 200px; /*any size*/
  overflow: hidden;
}

.object-fit-cover {
  width: 100%;
  margin-top: -50%;
}
<div class="container">
  <img class="object-fit-cover" src="https://jardim-plant-images-development.s3.amazonaws.com/hfj1h9jq2q8o8tyv1r6dxhi4zrmn">
</div>

I am hoping that I could use object-fit instead. Thoughts on this approach?

alvincrespo
  • 9,224
  • 13
  • 46
  • 60

2 Answers2

-1

You can write:

.container {
  max-width: 300px;
}

.object-fit-cover {
  object-fit: cover;
  width: 100%;
  height: 100%;
}
<div class="container">
  <img class="object-fit-cover" src="https://jardim-plant-images-development.s3.amazonaws.com/hfj1h9jq2q8o8tyv1r6dxhi4zrmn">
</div>
Mr. Hugo
  • 11,887
  • 3
  • 42
  • 60
  • The problem with this is that I'd like to keep the container a 200x200 or 300x300 box. I thought object-fit would keep the aspect ratio if I set it to cover. – alvincrespo May 02 '20 at 21:09
  • @alvincrespo So you think that `object fit: cover` respects the aspect ratio of the image? That assumption is incorrect. It does NOT, and instead tries to fit the image in a new aspect ratio (in your case the aspect ratio defined by its parent). – Mr. Hugo May 04 '20 at 18:50
-1

Just add position: relative to the container. This instructs its children that their width and height is relative to the width and height of this container (in this case 200 x 200 px).

.container {
  width: 200px; /*any size*/
  height: 200px; /*any size*/
  position: relative;
}

.object-fit-cover {
  width: 100%;
  height: 100%;
  object-fit: cover; /*magic*/
}
<div class="container">
  <img 
    class="object-fit-cover" 
    src="https://jardim-plant-images-development.s3.amazonaws.com/hfj1h9jq2q8o8tyv1r6dxhi4zrmn">
</div>

If you want it to be responsive, you should add an extra container:

.container {
  width: 100%;
  max-width: 300px; /*any size*/
}

.innercontainer {
  padding-bottom: 100%; /* 1:1 ratio */
  position: relative;
}

.object-fit-cover {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover; /*magic*/
}
<div class="container">
 <div class="innercontainer">
  <img 
    class="object-fit-cover" 
    src="https://jardim-plant-images-development.s3.amazonaws.com/hfj1h9jq2q8o8tyv1r6dxhi4zrmn">
 </div>
</div>
Mr. Hugo
  • 11,887
  • 3
  • 42
  • 60