inline block后不需要的空格dispite having no spaces in html [重复]

gwo2fgha  于 2023-09-28  发布在  其他
关注(0)|答案(2)|浏览(89)

此问题已在此处有答案

Image inside div has extra space below the image(10个答案)
6天前关闭
我知道inline blocks often have unwanted spaces between them because there are spaces in the html,我们可以设置font-size: 0或删除html中的空格来摆脱它们。然而,似乎当我们使用<img><canvas>标签(默认情况下有display: inline)时,即使我们在html中没有空格,我们也会得到不需要的空格:

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

上面的代码在浏览器中看起来像这样:

但是如果我用一个字符将它改为<span>,它就没有不需要的空格:

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

我仍然可以用font-size: 0line-height: 0去掉第一个中的空格,但是我想知道空格是从哪里来的。我甚至用JavaScript确认了标签中没有空格:

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

我也试过显式设置alt="”,以防它是一些隐藏的文本,但它仍然有空间。
编辑:澄清一下,我的问题是:*****我不是在寻找CSS技巧来消除空间,因为我已经在问题中指出了两个。

w6mmgewl

w6mmgewl1#

正如你在问题中指出的,在div上设置font-size: 0可以消除空格。
有很多实验可以尝试看看发生了什么。
例如,将div的font-size设置为100 px-空间变大。
将字符'xg'放入div中,您将看到图像与x的底部对齐。额外的空间由g的下降部分使用。
来自@schmauch的答案通过使img的底部与div的底部对齐来解决这个问题。但默认情况下,即使div中没有任何实际文本,也会将其与[文本]的基线对齐。

ycggw6v2

ycggw6v22#

当您将图像的垂直对齐设置为vertical-align: bottom时,空格将消失。

相关问题