views:

72

answers:

4

Are there any differences in performance or load/caching behavior when displaying images in img tags vs divs with image backgrounds?

My example:

I have a site with many overlapping images, some of which I will need to load dynamically with javascript. One issue is that I need to anchor the images to the right of the element, so that I can do a nice wipe-to-right effect. Because of this I was using a div with background image positioned right. Couldn't figure out how to do this with img but since divs are working for me I didn't know if this would matter...

+1  A: 

AFAIK, browsers cache images the same whether they're in a DIV or an IMG. In any case, I think this one of those cases where specific performance is defined as an implementation detail internal to each rendering engine (and possibly the browsers built around them). As such, it's both out of our control as designers/developers and subject to change from browser to browser and version to version. In other words, I wouldn't spend too much time worrying about it.

mr. w
+1  A: 

The only difference I can conceive of it this:

You can't scale images as backgrounds, although you can for img tags. This would open a scenario where background images loaded faster becuase it forces you to have the correct native size as opposed to downloading the entire image and scaling it. However, the converse could be true: given that you didn't care about image quality so much, you could deliver smaller imgs to your page and scale them up.

I'd stick with whatever rendered cleaner (and more consistently -- IE/FF/Chrome/Safari/etc).

Brad
Good point- thanks
Yarin
A: 

Technical differences yes, most notably you can set the width/height of an IMG tag and it will stretch the image, which can be useful in some situations.

The main thing you've got to keep in mind though is the context of the image within the HTML document. If the image is content, say an image in a gallery, I'd use a IMG tag. If it is just part of the interface I might use a div instead.

Paul
In CSS3, you can scale background images. See http://www.css3.info/preview/background-size/ for an example. That said, you bring up an excellent point about the semantic difference: an IMG is usually the better choice when the image is a material part of the page's content, while a CSS technique is usually preferred when the image is just decorative or for formatting.
mr. w
+2  A: 

The main performance difference is using background images allows you to use CSS sprites. Having one image contain a large number of images from your page means the user only has to make one request instead of one for each image.

path411
Good point- thanks
Yarin