3

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!

cpalmer
  • 1,107
  • 6
  • 10
  • It is not bug.. Inline-blocks renders with white spaces – Arda Jan 03 '14 at 20:03
  • Related posts: http://stackoverflow.com/questions/608172/block-level-elements-within-display-inline-block, http://stackoverflow.com/questions/5078239/how-to-remove-the-space-between-inline-block-elements, http://stackoverflow.com/questions/16678929/display-inline-block-what-is-that-space, http://stackoverflow.com/questions/1833734/display-inline-block-extra-margin – Aziz Shaikh Jan 03 '14 at 20:13

2 Answers2

1

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.

Terry
  • 63,248
  • 15
  • 96
  • 118
0

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

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

Fiddle

Arda
  • 470
  • 5
  • 10
  • If you change it to "
    x
    " with a single letter in the b div then the extra space goes away. So it can't be that inline-block element always have that space. It seems there is something even stranger at play.
    – cpalmer Jan 03 '14 at 20:14