Search code examples
cssimageresponsive-designdimensionsaspect-ratio

Give dummy image natural width and height to act responsively


I'm using jQuery Lazyload Plugin. Before the images are loaded I use a dummy image as placeholder which is a 20x20 pixels blank PNG. Also I'm using jQuery wookMark which is a dynamic grid plugin. For this plugin to work I need the images to be in their correct aspect ratio so the plugin can calculate the suitable position of each grid element in the page.

I have width and height attributes on img tag set to the correct dimensions, but that doesn't have any effect on the dummy image and it will be shown as a square, no matter what.

I can use inline styles to set width and height for each image, but this approach will stop the image from being responsive in other dimensions.

Is there a way to give an image width and height in a way that it act like it is its real dimensions?

Here's the pen to look at: http://codepen.io/anon/pen/iaIoJ


Solution

  • I found a good way for it.It's not going to be pure css, but that's fine by me :)

    My solution is to set the image height to 0 and use padding-bottom to maintain the aspect ratio:

    <img src="./blank.png" style="height:0;padding-bottom:133.333%">
    

    And also having a class for the img tag when the actual image is loaded:

    img.loaded {
        height:auto !important;
        padding-bottom:0 !important;
    }
    

    Here's the pen for this example: http://codepen.io/nOji/pen/yoshA

    Hope you find it useful.