1

I have a grid layout with 3 columns that roughly span 33% of the page width each - I'd like to have a square image at the top of each column but have no control over the images actual aspect ratio.

I'm currently using object-fit:cover; to crop the image to a specific size (400px x 400px) but now that image doesn't scale with the column width.

How to make sure the cropped image fit inside the column while keeping its new aspect ratio?

div {
  width: 33.33%;
  border: 1px solid blue;
}

div > img {
  width: 40rem;
  height: 40rem;
  object-fit: cover;
}
<div>

  <img src="https://via.placeholder.com/480x800">

</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Tony Merryfield
  • 383
  • 3
  • 10
  • Please add relevant code so we can assess the issue – Luuuud May 26 '20 at 12:34
  • @LuudJacobs - trimmed down code added. I would like the img to retain its new aspect ratio, but also scale to fit the parent width. – Tony Merryfield May 26 '20 at 12:49
  • 1
    @dippas - I don't think either of your 'duplicates' answer my question - I'm not looking to retain the aspect ration, I wanted to change the aspect ratio but still allow it to scale. Big difference... – Tony Merryfield May 26 '20 at 15:26
  • and now you have another completely irrelevant duplicate. Not sure how the usage of object-fit is related to your issue since you are correctly using it. – Temani Afif May 26 '20 at 22:11
  • @TemaniAfif - not sure if that comment was for me, I was happy with my usage of object-fit, it was simply making it also scale that was my problem. Happy to change the title of it isn't clear enough. – Tony Merryfield May 27 '20 at 21:28
  • it's not for you but for the new duplicate (https://stackoverflow.com/questions/34247337/object-fit-not-affecting-images) added after the ones you complained about ;) any way, I reopened the question since the duplicate was irrelevant. – Temani Afif May 27 '20 at 21:31
  • Cool, thanks (I know thanks responses are frowned upon but I feel it is something I need to communicate when someone helps me!) – Tony Merryfield May 27 '20 at 21:36

1 Answers1

3

You may need an extra div to achieve this:

.col {
  width: 33.33%;
  float: left;
  border: 1px solid;
  box-sizing: border-box;
}

.col > div {
  position: relative
}

.col > div::before {
  content: "";
  display: inline-block;
  padding-top: 100%;
}

.col img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="col">
  <div><img src="https://via.placeholder.com/480x800"></div>
  <p>some text here</p>
</div>
<div class="col">
  <div><img src="https://via.placeholder.com/480x1200"></div>
  <p>some text here</p>
</div>
<div class="col">
  <div><img src="https://via.placeholder.com/600x400"></div>
  <p>some text here</p>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415