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>

7
  • Please add relevant code so we can assess the issue
    – Luuuud
    May 26, 2020 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. May 26, 2020 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... May 26, 2020 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. May 26, 2020 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. May 27, 2020 at 21:28

1 Answer 1

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>

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.