Pascal Klein Pascal Klein - 1 month ago 3
CSS Question

CSS Image Layouting before image loaded

For my mobile website I want to show images of different but known heights/widths with two constraints:

  • The image should take up the whole width of the browserview

  • The height should be scaled (down or up) accordingly to keep the proportions

As soon as the browser downloads the image, it is really easy with the following CSS:

<img src="myImageURl" style="width: 100%; height: auto;" />

But because the loading of the image takes some time, I want the browser to layout the image before it downloads it. So the browser does not need to rerender the page, once he fetches the image. I tried the following approaches, which failed:

// 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;" />

I would love some help here. But please in CSS, I don't want to use Javascript / jQuery if I don't have to.


I guess I am not the only one with this problem:


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="…">

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 height/width*100.)

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.