0

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:

  1. Attempting to use the same div trick, except applying the width: 100%; padding-top: 100% to the <img> tag. This does not work.
  2. 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.
Kevin Shi
  • 496
  • 1
  • 7
  • 18
  • 1
    make the image position:absolute inside the div. Check the end of the accepted answer: https://stackoverflow.com/a/10441480/8620333 – Temani Afif Sep 24 '20 at 00:49
  • @TemaniAfif Brilliant. – Kevin Shi Sep 24 '20 at 00:53
  • if you specify a width of `100%` make sure you remove the `height` property completely. if you want the image to go 100% but not more than a specific width you can use CSS class `.myImage{max-width:200px}` then apply the class to the image. If you remove height it will always inherit the original image dimensions regardless of width. – Brian Wiltshire Sep 24 '20 at 00:56

1 Answers1

0

This can be done using the following HTML/CSS, thanks to the commenters.

HTML:

<div class="wrapper">
  <img class="image" src="img.png" />
</div>

CSS:

.wrapper {
  position: relative;
  width: 100%;
  padding: 100%; /* change this based on your desired ratio */
}

.image {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
Kevin Shi
  • 496
  • 1
  • 7
  • 18