cssimagelazy-loadingdata-uri

Data URI image sizing (auto height)


I use Unveil.js to lazy load images. To save time/space, I use a base64 placeholder image:

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="https://unsplash.it/1000/500?image=631" width="1000" height="500" data-unveil="true" />

The problem I'm experiencing is how the placeholder image gets resized. It seems to always maintain an aspect ratio of 1 which is a problem for responsive sites.

So if the image tag above is inside of a <div> with a width of 50% and the <div>'s calculated width is 500px (total viewport width is 1000px) then the image will overflow the <div> unless I use max-width: 100%; height: auto; and then a non-data URI image will correctly scale and maintain its aspect ratio.

However, the data URI image always remains square, regardless of width/height attributes in the <img> tag or CSS rules. This causes some jumping around on slower servers because the image that gets lazy-loaded by Unveil.js is not always square.

I set up a quick fiddle to demonstrate the sizing differences (without Unveil.js): http://jsfiddle.net/silb3r/7bnfqkko/1/

And one with Unveil.js: http://jsfiddle.net/silb3r/2eff5thm/ (you may need to manually throttle your connection to see the issue)

Is anyone familiar with a way to ensure that the data URI maintains the aspect ratio of the original image? Preferably without adding more jQuery, but I am open to anything.

Thank you for any suggestions.


Solution

  • Well, your CSS overwrites the width and height set via HTML attributes, and so the intrinsic image dimensions come into play, and those are 1×1 pixels. And therefor setting height:auto naturally results in a square image, no matter what.

    If you know the aspect ratio for your images beforehand (and you seem to do, assuming those width and height HTML attribute values you used are not completely arbitrary – otherwise, a few lines of server-side code could read them from the image files, if it needs to be more dynamic), then you can use what’s called the “padding-top hack” to create a placeholder that will use the correct aspect ratio.