Previous Section  < Day Day Up >  Next Section

Recipe 6.4 Removing Gaps from Table Cells with Images

Problem

You want to get rid of space in a table cell that contains only an image. You want to go from Figure 6-2 to Figure 6-3.

Figure 6-2. A gap appearing below an image in a table cell
figs/csscb_0602.gif


Figure 6-3. Displaying an image in a table cell as a block-level element
figs/csscb_0603.gif


Solution

Set the image to be displayed as a block-level element:

td img {

 display: block;

}

Discussion

We set the element to block content because the whitespace at the bottom of the image occurs because the image element is supposed to contain inline content, possibly text. The browser puts the image on the baseline used for text content even if there is no text in the content. This baseline isn't at the bottom of the cell because some letters (e.g., g, p, q, and y) have descenders that hang below that baseline (see Figure 6-4).

Figure 6-4. The lowercase letters g, p, q, and y
figs/csscb_0604.gif


You can't get rid of the descender space, because the baseline is a percentage of the total font size. Therefore the only way to place images without a baseline is to set the display property for the image to block as shown in the Solution.

A Document Type Definition (DTD) is a formal statement that defines the relationship of elements used in a web page. For example, there are differences in the HTML2 DTD compared to the HTML 4.1 DTD. Those differences are spelled out in their own DTD. A browser can determine which DTD to use when rendering a page by a small statement that precedes any markup in a web page.

There are certain DOCTYPEs that will put the browser into standards mode instead of quirks mode.

Having the browser in standards mode ensures the gap between images and table cell borders. Use alternative DOCTYPES that trigger quirks mode but that still validate to avoid this gap or if you simply want to avoid standards mode. For more information, see a chart comparing DOCTYPEs and browsers at http://www.webstandards.org/learn/reference/doctype_switch.html.

There might be times when setting the image's display to block isn't the best solution to removing whitespace around an image in a table cell. If that turns out to be the case, another method to remove the space is to set the image's vertical-align property to bottom as long as the image is taller than the line box.

See Also

The CSS 2.1 specification for the display property at http://www.w3.org/TR/CSS21/visuren.html#propdef-display; "quirks" mode at http://www.mozilla.org/docs/web-developer/quirks/; "almost standards" mode at http://devedge.netscape.com/viewsource/2002/almost-standards/.

    Previous Section  < Day Day Up >  Next Section