For my mobile website I want to show images of different but known heights/widths with two constraints:
<img src="myImageURl" style="width: 100%; height: auto;" />
// The image is not layouted before fetched
<img src="myImageURl" height="myImageHeight" width="myImageWidth" style="width: 100%; height: auto;" />
// The image is layouted, but wrong: height is not proportional to the width anymore
<img src="myImageURl" style="width: 100%; height: myImageHeight;" />
As Pete already said, you can not do any (automatic) calculations before the image is downloaded, so the browser knows its width and height.
But since you are able to determine the aspect ratio of the image beforehand, you could try a “workaround” by adding an extra placeholder element around the image – and make use of the fact that
padding values given in percentage always are calculated based on the width of an element, even for padding-top/-bottom.
That could look something like this:
<div style="position:relative; width:100%; height:0; padding-top:50%;"> <img style="position:absolute; top:0; left:0; width:100%;" src="…"> </div>
This is a
div element with no height, but a padding-top – that will give it an actual “height” of 50% of the computed 100% width. (That would be for an image with an aspect ratio of
2:1 – for
3:1 the padding-top value would have to be 33.333% accordingly – and so forth, basically
That should span up our placeholder even before the image is loaded.
The image itself is positioned absolutely inside this relatively positioned placeholder – that makes sure it gets displayed at the same position in the document.
The only thing that might be problematic is rounding that has to occur for values with decimal points – 33.333% of 1000 pixels would be 333.33 pixels, and the browser has to round that down to 333 pixels. Should the resized image have an actual height of 334 pixels however, it would just flow out of the area the placeholder div is spanning up by that one pixel. May depend on the actual layout (and your fetish for pixel-perfect accuracy) whether that’s acceptable or not.