5

I have the following code, and it allows the red to show through from the a element. Why is this. I would have expected that the a element would only expand to the size of the contents but it looks like it's a bit bigger than that. See the codepen here http://codepen.io/anon/pen/soqEz.

HTML

<a href="#"><img src="http://placehold.it/150x150" /></a>

CSS

a{
  background: red;
  margin-bottom:0;
  padding-bottom:0;
  border-bottom:0;
}
img {
  margin-bottom:0;
  padding-bottom:0;
  border-bottom:0;
}

EDIT: I see the answers below ... but can anyone also explain why the space is there AT ALL ( I mean given that it's a block level element ... what's the purpose of it in the first place ) ... as opposed to trying to get rid of it. Thanks

byronyasgur
  • 4,627
  • 13
  • 52
  • 96
  • Given your question edit, the reason is explained in the accepted answers of the two linked questions in the above comments by @Quentin and myself. – ajp15243 Apr 03 '13 at 19:43

4 Answers4

9

The img element is inline by default. inline elements act as text and default to a vertical-align: baseline. This means that the bottom of the image aligns with the bottom of your text. Notice that a lower case p or g goes below the bottom of the vertical text alignment. You can fix it by either adding vertical-align: bottom OR display: block.

Daniel Moses
  • 5,872
  • 26
  • 39
  • 1
    Images are inline-block by default, not inline. – cimmanon Apr 03 '13 at 19:44
  • @cimmanon my browser is defaulting it to `inline`. Source for inline-block? – Daniel Moses Apr 03 '13 at 19:52
  • 1
    Inline elements don't honor properties like margin, height, or width, while inline-* elements do. – cimmanon Apr 03 '13 at 19:58
  • 1
    @cimmanon - No, they are "replaced inline" not "inline-block". "inline-block" boxes have an internal structure that can affect the baseline of the box, "replaced inline" have opaque internals, but will otherwise honour the properties you mention, similar to "inline-block" and not like "non-replaced inline" which don't. – Alohci Apr 03 '13 at 20:13
  • See, for example how in http://www.w3.org/TR/CSS2/visudet.html#Computing_widths_and_margins, the width property handling requirements are very different for replaced and non-replaced inline boxes. – Alohci Apr 03 '13 at 20:27
3

It does this because it's an inline element. Change the display type

img {
    display:block;
}
Kevin Lynch
  • 24,427
  • 3
  • 36
  • 37
2

because the image is an inline element by default. Add display: block to your img rule and see.

Ejaz
  • 8,719
  • 3
  • 34
  • 49
0

In your case you need to add display:block, but to the image tag instead of the link tag. add

img
{
display:block;
}
trajce
  • 1,480
  • 3
  • 23
  • 38