21

I created a new document both with xhtml 1.0 and html 4.01 STRICT just to isolate this. All I have in its body is:

<div style="border: blue 3px solid;">
<img src="testimage.jpg" width="800" height="400">
</div>

The result is normal except there's a 5px space below the image that goes away if I change the doctype to transitional. It also goes away if I set display: block to the image.

You can see the result yourself here (I know the white space on the right is normal since its a block element): http://i52.tinypic.com/2prd1jd.jpg

I tried setting margin/padding to 0, even this:

*
{
   margin: 0; padding: 0;
}

but it's still the same.

Can anyone please explain this behavior?

John
  • 898
  • 2
  • 9
  • 25
  • My guess is the display: inline is preserving whitespace - what happens if you remove all line-breaks from your markup? – kinakuta Jun 19 '11 at 20:45
  • oops, this property shouldn't be there since img tags are inline by default :). Unfortunately that doesn't solve the problem. – John Jun 19 '11 at 21:21

2 Answers2

48

It has to do with vertical alignment of the image. Try this:

img{
 vertical-align: top;   
}

and the space will go away.

To clarify, if you put some text next to the image you will see the issue. The image is aligning with the base of the text but letters like y and g will go below that line. The extra space is for those overhanging letters.

James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • Thanks this did the trick! I still don't understand however why does this happen only in strict doctypes and not in transitionals. I mean what's the logic behind it? – John Jun 19 '11 at 21:23
  • I'd have to look into the specification but I suspect there is some standard around either image or display:inline that defaults it to `vertical-align:baseline`, it may even be the default for all elements. Strict adheres to the standard and quirks doesnt. – James Montagne Jun 20 '11 at 00:40
  • Suprising that in all browsers it is happening and nobody fix the engine of browser to treat the image as div. "By default, an image is rendered inline" but still why space? anyhow, your answer helped, we can move on. Thanks! – Pawel Cioch May 20 '14 at 22:18
5

This is because, as mentioned by @Pawel, "by default, an image is rendered inline". Since it is "inline" some spaces below will be given for characters like 'g,j,q,y' etc. enter image description here

So another solution is just set the image as block:

img {
  display:block;
}

An example is here: https://gist.github.com/MrCoder/450783bc33d6b412075d

Devs love ZenUML
  • 11,344
  • 8
  • 53
  • 67