I want to have my image always have a fixed aspect ratio (1:1 in my use case, but an ideal solution would work for any aspect ratio) such that the image always takes 100% of the parent's width (which is not static), and the height is calculated based on the given aspect ratio.
I am aware of the CSS trick of using a <div>
with styles width: 100%; padding-top: 100%;
and then setting the image as the div's background via a CSS url, however I would like to do this with the built-in image tag. My reason is that I am using the onload
and onerror
properties of the <img>
tag, and these would be lost using the div trick.
I have tried the following things:
- Attempting to use the same div trick, except applying the
width: 100%; padding-top: 100%
to the<img>
tag. This does not work. - Retrieve the width value of the parent, then setting the height value of the image using JavaScript. This works, but a CSS solution would be much nicer.