skip to Main Content

I know inline blocks often have unwanted spaces between them because there are spaces in the html, and that we can set font-size: 0 or remove the spaces in html to get rid of them. However, it seems like when we’re using the <img> or <canvas> tag (which have display: inline by default), we get the unwanted spaces even if we have no spaces in the html:

<body style="margin: 0">
  <div style="background-color: pink"><img style="width: 50px; height: 50px; background-color: skyblue" /></div>
</body>

The code above looks like this in the browser:

unwanted space after of an inline block

but if I change it to <span> with a character, it does not have the unwanted space:

<body style="margin: 0">
  <div style="background-color: pink"><span style="background-color: skyblue">B</span></div>
</body>

no unwanted space after inline block

I can still get rid of the space in the first one with font-size: 0 or line-height: 0, but I’m wondering where the space came from. I even confirmed with javascript that there are no whitespaces in the tag:

document.querySelector("div").innerText // returns ""

I’ve also tried explicitly setting alt="" in case it was some hidden text but it still had the space.

Edit: To clarify, my question is: why is the space there in the first place? I’m not looking for CSS tricks to get rid of the space, as I’ve pointed out two myself in the question already.

2

Answers


  1. When you set the vertical alignment of the image to vertical-align: bottom the space vanishes.

    Login or Signup to reply.
  2. As you have pointed out in the question, setting font-size: 0 on the div gets rid of the space.

    There are various experiments you can try to see what is happening.

    For example set div’s font-size to 100px – the space gets bigger.

    Put the characters ‘xg’ in the div and you’ll see that the image aligns with the bottom of the x. The extra space is used by the g’s descender.

    The answer from @schmauch solves the problem by making the img have its bottom aligned with the bottom of the div. But the default is to align it with the baseline [of text] even if there isn’t any actual text in the div.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search