71

I have an tag surrounding an image. I have a border set on the div that the tag is in. I have both margin and padding set to 0 but for some reason my tag is still about 3 pixels taller than my image. This leaves a bit of space between the image and the border, which destroys the look that I want to accomplish.

What am I doing wrong? I have tested in both FireFox and Chrome with the same results. Thanks

Icode4food
  • 8,504
  • 16
  • 61
  • 93

5 Answers5

122

The image is display: inline so it is treated like a character and sits on the baseline. The gap is caused by the space provided for the descender (which you find on letters like j, g, y and p).

Adjust the vertical-align with CSS: img{vertical-align: bottom}

Marcin
  • 48,559
  • 18
  • 128
  • 201
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 11
    More specifically, `img{vertical-align: bottom}` – Álvaro González Jul 07 '10 at 18:17
  • 1
    That is exactly what is happening. The issue is resolved if I do `vertical-align:bottom;` or `display:block;`. Which is the better solution? – Icode4food Jul 07 '10 at 18:18
  • Neither is better, they just have different implications. Block elements have line breaking around them and other fun side effects. – Quentin Jul 07 '10 at 18:38
  • The critical one is setting vertical-align to bottom. 9 years passed after this question asked, but I am still curious on why vertical-align affects the height – cytsunny May 17 '19 at 02:28
15

display:block is sufficient for this, if the element has no siblings.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
2

I had the same issue and i fixed it by adding to the 'a' tag display: block; and font-size: 0px;

christk
  • 834
  • 11
  • 23
2

I fixed mine by adding

a {
 display:inherit
}

Hope this helps

David Buck
  • 3,752
  • 35
  • 31
  • 35
0
December 2021 Solution

As announced by several people, css :has() selector was implemented. So this issue could be solved for anchors which "has" images as a direct child:

a:has(> img) {
  font-size: 0;
}

At the moment I am writing this reply, it is only supported by Safari TP but probably this table will be greener soon.

Lionel T
  • 1,559
  • 1
  • 13
  • 30