Gropai Gropai - 2 months ago 8
CSS Question

Vertical space of span expands in the containing div when it's set to be an inline-block

I have a span embedded in a div like this :



div {
width: 50px;
height: 50px;
background: red;
line-height: 50px;
}
span {
background: yellow;
}

<div>
<span>text</span>
</div>





It works well. However, if I set the span to be
display:inline-block
, the background color of the span expands to fill up the vertical space of the div. Why?

Answer

Because span by default is an inline element. As soon as it becomes an inline-block`, its height will adjust to the full line-height.

In the following example I created two inline-block spans and left the third one at the default inline. The first inherits the line-height 50px from the container, the second has a defined line-height of 40px, which is less than the line-height of the container and therefore leaves some vertical space above and below. The third again has the inline property (which would be the default if span were not defined as inline-block before) and only covers height of the text itself since it's inline.

http://codepen.io/anon/pen/GjAPqg

<div>
  <span>text1 inline-block line-height 50px</span>
  <span class="span2">text2 inline-block line-height 40px</span>
  <span class="span3">text3 inline</span>
</div>

CSS:

       div {
          width: 200px;
          height: 100px;
          background: red;
          line-height: 50px;
        }

        span {
          background: yellow;
          display: inline-block;
        }

        .span2 {
          background: green;
          display: inline-block;
          line-height: 40px;
        }
        .span3 {
          background: aqua;
          display: inline;
        }