Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Setting the size of Div to be the same as its Child (before the child loads)

Setting the size of Div to be the same as its Child (before the child loads)

Problem

I have a parent div .photo_container that holds an img, and stretches to the dimensions of this img with its display: inline-block CSS attribute.

Problem: Because there will be many .photo_container divs on the page and the images take some time to load, before all the img loads, the page will be filled with the tiny unstretched divs (with a few px of padding) before expanding to accomodate each img as they load one by one.

Is it possible to 'pre-stretch' the divs to the correct size so that when its child img loads, it does not have to change its size?

Here's an illustration of how it looks like before the images load (ugly!) and after.

Code:

Problem courtesy of: Nyxynyx

Solution

There is no way to know image dimension unless you actually load the image (in JS or CSS alike). So it doesn't matter if you use JS and set container dimensions dynamically - you still need to load image first and thus for some time you will display the "ugly" empty containers.

So, add minimum size to .photo_container. I looks like at least width of all your thumbs is consistent, so do something like .photo_container { min-width:100px; min-height:50px }. Then to each image add an onLoad callback that will resize parent accordingly.

If you use jQuery, do something like this:

$('.photo_container img').each(function() {
  $(this).bind('load', function() {
    var w = $(this).width(),
        h = $(this).height();
    $(this).parent('.photo_container').attr({ width: w+'px', height: h+'px' });
  }
});
Solution courtesy of: mvbl fst

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

Setting the size of Div to be the same as its Child (before the child loads)

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×