That mysterious gap under images

Example 1

This first example illustrates the gaps that can be a PITA to get rid of if you don't know where they come from. I'm using an <object> element because the original question at Dev Shed CSS forum was about the gap under a Flash object IE has such poor support for the <object> element that the demo now uses the <img /> element instead.

The gap is caused by the default vertical alignment of inline elements. A thorough explanation of inline formatting may be found on Eric Meyer's site. Basically, the bottom of the object lines up with the baseline of the parent element text. The parent text is implicit if there is no actual text. Text in the sample containers is 2× the base size to make the gap more obvious.

There is a second gap due to the top and bottom margins of elements like <hn> and <p> and due to a phenomenom known as collapsed margins. Margin collapse will be dealt with in another demo. It is shown in this first example for information only.

Generic Header

Example 2

This is just like example 1, except that some inline text follows our <img /> element, so you can see the descenders.

some text qypgj

Example 3

This time we set the vertical-align property of the <img /> element to bottom. This aligns the bottom of the <img /> with the bottom of the line box, eliminating the small gap we saw earlier.

some text qypgj

Example 4

This time we set the display property to block. This eliminates the gap, and may be a good fix in many cases.

But, it may cause problems of its own, as each block element wants a line all to itself. Notice the text is forced below the image.

qypgj

Example 5

Another way to make the image block is to float it.

some text

As you can see, two things happen. First, the text now aligns to the top of the float element. If this is what you want, all is well. If not, the inline vertical-align is called for. The second thing is you will likely want the floated image to be contained by its parent. In this case, we can simply set the parent <p> to {overflow: hidden;}.

For IE≤6, you can apply Claire Campbell's Tripswitch Hack.

any text