There is a gap below the bottom of an inline image element

There is a gap below the bottom of an inline image element

If you have an inline image within a container, you will notice that there is a gap below the bottom of the image. For example, the markup

  1.   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  2.     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  3.   <html xmlns="http://www.w3.org/1999/xhtml">
  4.   <head>
  5.     <title>Untitled</title>
  6.     <style type="text/css">
  7.       p { background: #aaaaaa; width: 250px; float: left }
  8.     </style>
  9.   </head>
  10.   <body>
  11.     <div>
  12.       <p style="margin-right: 3px">
  13.         <img src="./sample.jpg" alt=""/>
  14.         <span style="background: red">og中文</span>
  15.       </p>
  16.       <p>
  17.         <img src="./sample.jpg" alt=""/>
  18.       </p>
  19.     </div>
  20.   </body>

is rendered as

Fig. 1.  Inline images by default align with the baseline of a line box.

where we can see that the image on the left aligns with the bottom of the character 'o', not the bottom of 'g'. The former marks the baseline of the line box. Note that the image on the right aligns with the baseline even when there is no character on the same line. That's where the gap comes from.

The red background highlights the height of the line box in the span element. As the container of the texts, the span element itself aligns with the bottom of its container. Within the span element, the gap above the top of 'o' and 'g' is reserved for characters such as 'h' and 't'. The line height of the image is the height of the image plus the baseline gap. So images and texts have different line heights.

The baseline is for letters. I put some chinese characters next to the letters, but it looks like they have their own baseline depending on the font, and the images do not align with it.

Now that we know it is the line box, we can use the text properties in CSS to control it. Specifically, we set the "vertical-align" property to a value other than "baseline". Say,

  1. img {
  2.   vertical-align: top
  3. }

In the CSS3 draft, there are linebox properties for fine-grained control. However, those have not been well supported among popular browsers so far.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

More information about formatting options

To prevent automated spam submissions leave this field empty.