简体   繁体   English

显示块和内联块之间的间距差异

[英]Difference in spacing between display block and inline-block

Came across something very curious today I can't figure out the reason for. 遇到一些非常好奇的东西,我无法弄清楚原因。

For this HTML: 对于这个HTML:

<div class="a"><div class="b"></div></div>

And CSS: 和CSS:

.a {
    background: blue;
}

.b {
    display:inline-block;
    height: 30px;
    width: 30px;
    background: red;
}

I would expect the outer "a" div to be just as tall as is needed to contain "b", 30px tall. 我希望外面的“a”div与包含“b”,30px高所需的一样高。 But when rendered "a" is 35px tall. 但当呈现“a”是35px高。 There are 5 pixels of emptiness below "b". “b”以下有5个空白像素。 Why? 为什么?

See http://jsfiddle.net/Pb2q9/ I've tried this on Chrome and Firefox and they both give the same output. 请参阅http://jsfiddle.net/Pb2q9/我在Chrome和Firefox上尝试了这一点,他们都提供相同的输出。

Curiously if you change "b" to be display:block that extra space at the bottom goes away. 奇怪的是,如果你改变“b”来显示:阻止底部的额外空间消失。 Can anyone explain why these two scenarios render differently? 任何人都可以解释为什么这两种情况呈现不同 What is it about inline-block that dictates that 5px of space should exist? 什么是内联块,它规定5px的空间应该存在?

EDIT: 编辑:

Stranger still I found that if you change the HTML to 奇怪的是,我发现如果你改变HTML

<div class="a"><div class="b">x</div></div>

Note the single "x" character in the b div the extra 5px at the bottom goes away! 注意b div中的单个“x”字符,底部的额外5px消失了!

It is a normal behaviour of inline block elements. 这是内联块元素的正常行为。 There is always white space. 总是有空白空间。 If you want to remove white space of element, change fontsize of parent container to 0px 如果要删除元素的空格,请将父容器的fontsize更改为0px

.a{font-size:0px;}
.b{font-size:16px;}

Fiddle 小提琴

The vertical white space you see is due to the line-height property in play. 您看到的垂直空白区域是由于游戏中的行高属性。 If you set line-height: 0 on the parent element, you can see that the spacing goes away - http://jsfiddle.net/Pb2q9/9/ 如果在父元素上设置line-height: 0 ,则可以看到间距消失 - http://jsfiddle.net/Pb2q9/9/

When working with inline-block elements and yet wanting to achieve the layout behavior of block-level elements, remember to set both font-size and line-height to 0. 使用内联块元素但又想要实现块级元素的布局行为时,请记住将font-size和line-height都设置为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM