How to
Get Rid of Spaces
Between Images
in HTML

We all know how to get rid of spaces between images when laying out images with the <table> tag. Just set the cellpadding, cellspacing, and border attributes to zero.

But what happens if you've already set all the <table> attributes that control spacing to zero and you still have spaces between your images? What do you do then?

This errant space could be a vertical space or a horizontal space. A horizontal space will go lengthwise across the page and a vertical space will go lengthwise down the page.

Vertical or horizontal, the key question to ask yourself is: What causes this space and what can I do about it?

First, a little background information: An image is just another character on a line. In HTML, this can have important consequences.

Because an image is just another character on a line, some browsers assume that the line does not end with the image. What do these browsers do in this situation? They either add a character after the image or they add a line after the image.

If the browser adds a line after the image, you end up with a small horizontal space between your images that are stacked one on top of another. If the browser adds a space after the image, you end up with a vertical space between your images that are placed side-by-side.

The solution to this problem? Place a <br> (break tag) immediately following the image. This should fix the problem if you have a horizontal space between stacked images. If the problem is a vertical space, place a &nbsp; (non-breaking space character) immediately following the image.

Someday you may not have to do this as not all browsers have this problem. For now, the placing of a character or a line break after the image solves the problem.

In some cases, Internet Explorer will place a horizontal space (going across the page) between vertically-stacked images if you do not place your opening and closing <td> (table data) tags on the same line. Placing your opening and closing <td> tags on the same line as your table data seems to solve this problem.

You'll also get a vertical space between images if you put your <img> tags within the same <td> element on separate lines. Why? Because the newline separating one <img> element from another counts as a space. This space manifests visually as a vertically elongated space between your images.

Once again, the solution to the problem is simple: Place <img> tags that share the same <td> tag on the same line.

Further Reading

Making Text and Images Play Nice Together in HTML

©Edward Abbott, 2002-2004. All rights reserved. Revised June 9, 2004.

Questions or comments? Email me at ed@WebSiteRepairGuy.com.