Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in spacing between display block and inline-block

Tags:

html

css

layout

Came across something very curious today I can't figure out the reason for.

For this HTML:

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

And 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. But when rendered "a" is 35px tall. There are 5 pixels of emptiness below "b". Why?

See http://jsfiddle.net/Pb2q9/ I've tried this on Chrome and Firefox and they both give the same output.

Curiously if you change "b" to be display:block that extra space at the bottom goes away. Can anyone explain why these two scenarios render differently? What is it about inline-block that dictates that 5px of space should exist?

EDIT:

Stranger still I found that if you change the HTML to

<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!

like image 577
cpalmer Avatar asked Mar 13 '26 12:03

cpalmer


1 Answers

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/

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.

like image 157
Terry Avatar answered Mar 15 '26 02:03

Terry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!