How to contain image to fit this div

I’m questioning whether this is really even possible.
I want this image to nicely fit inside this 60% height of that div. But still to keep aspect ratio like it does in this (but doesn’t fill out nicely (stretches)). I don’t want to distort it by stretching

Screenshot_2024-01-20_15-13-34
That’s when I have:


.item > div > img {
  border: 0;
  object-fit: contain;
  
  width: 80em;
  height: 100%;
  
}

.item_div {
  width: 100%;
  height: 60%;
  
  
  
  border-radius: 12px 12px 0 0;
  overflow: hidden;
}


For now, I only managed to make this, it works somewhat okayish for PC layout, but for mobile layouts, it’s not nicest as it could be.


(on mobile it’s: )
Screenshot_2024-01-20_15-17-44

(note: if title is longer, it would use estate of image (so would move up, it wouldn’t stretch container div))

That is (which I currently have):


.item > div > img {
  border: 0;
  object-fit: contain;
  
  
}

.item_div {
  width: 100%;
  height: 60%;
  
  
  
  border-radius: 12px 12px 0 0;
  overflow: hidden;
}

css style and component

repo

For an image to fully fill a space that isn’t the same as its aspect ratio you would need to use object-fit:cover (not contain). Then the image should be sized at height:100% and width:100% to fit its container.

.item > div > img {
  object-fit: cover;
  width:100%; 
  height:100%;
}

Of cousre if the space is not the same as the image’s aspect ratio then the image is automatically expanded on both directions until the space is filled completely and then cropped to that size. That’s what the value cover will do, On the other hand contain will make sure all the image is inside the space which means that when aspect ratios don’t match there will be gaps as will happen when resizing.

Those are the only two options to handle images of different aspect ratios in predefined spaces.

If your images were all the same aspect ratio then you could responsively create the space at that exact same aspect-ratio (using the aspect-ratio property).

If you want more specific help then assemble a demo in codepen or similar so that we can offer code more easily. :slight_smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.