# An image placement problem to watch out for in Google Chrome

March 22, 2012

Google Chrome has an interesting little thing that it does, where it decides how the page will be laid out before it knows the dimensions of all the elements. For example, if you create a <div> tag with a large image in it, Chrome will calculate the height of the div before the image has loaded. That’s right - it figures out the height of the image’s container without necessarily knowing the size of the image.

So who cares? What does this mean?

Well, if you have elements styled as position: absolute in your page, you might find that they start out correctly placed, but they don’t move with the rest of the page when the image loads. This means that you have badly placed images sitting around in your page, making the whole thing a horrible mess.

Alternatively, you might have a set of images that are meant to sit in a nice little row inside a <div>, but they end up wrapping onto an extra line because Chrome didn’t wait until they’d loaded before it figured out how wide to make the <div>.

And what can you do about it? Here are a couple of options:

• Specify the dimensions of your images in code. Don’t leave it to the image to tell the browser what size it is, because by the time the browser finds out, it may well be too late.
You can do this in a couple of ways:
• Use the width and height attributes of the <img> tag. This is not very good in terms of separation of concerns, but it will get the job done.
• Use CSS to specify the width and height of your image, or alternatively the size of its container. This is better separation of concerns, and CSS should load early enough in the rendering process that you don’t get the same problem you’ve been having with your images.
• Use CSS image sprites instead of individual image files. This is basically the same as using CSS to specify your image dimensions, or rather it includes same. Image sprites force you to specify the size of the image, otherwise it won’t display correctly. This means that you will notice while you’re working on the page if something is not quite right, and be able to fix it there and then. You won’t have to waste time later on, coming back to somewhere you’ve already been.

Hopefully this helps you figure out a problem some time. If not, just remember it was here.

An image placement problem to watch out for in Google Chrome - March 22, 2012 - Lucas Wilson-Richter