2 years ago

#23049

test-img

Laura

How can I keep aspect-ratio of img in Safari based on parent height

I have been developing a website with 3 rows. The rows change in height, depending on which one is selected (let's say 20vh when not selected and 40vh when selected).

Inside the rows are blocks containing images like this:

<div class="row">

<div class="block">
<div class="image-wrapper">
<img />
</div>
</div>

<div class="block">
<div class="image-wrapper">
<img />
</div>
</div>
...

</div>

My problem is making the images keep a good aspect-ratio in Safari when the rows are changing height.

In other browsers I have used the aspect-ratio css property, but it is only supported in the latest version of Safari, which I cannot just assume everyone will have.

The other trick would be the "Netflix padding trick", where you put a padding-bottom to have the right height for your images. Unfortunately this trick doesn't seem to work when applied the other way around, with a 100% height and a padding-right. The blocks end up being 0px wide.

I also tried to make the <img> height:100% and width: auto, but then the width is set perfectly for 20vh, and not adapted when parent changes to 40vh.

Here is a codepen, without the aspect-ratio attribute, which allows you to see the problem even on Chrome or Firefox: https://codepen.io/laurapiccolo/pen/KKXxYrj

Does anyone have any idea how to fix this?

Thanks!

css

image

safari

responsive

aspect-ratio

0 Answers

Your Answer

Accepted video resources