Search code examples
htmlcssvertical-alignment

Vertical centering various sized spans with line-height


I want to gain a deeper understanding of how line-height works, in particular with centering text vertically within a fixed height element. In the example link below, you can see that setting the line-height to be equal to the container's height will center items as long as the items are all of the same size. When you put two different sized spans in, then the larger one will be centered, while the other will not be. I am at a loss to explain this, since both the large and small elements work separately. How can I accomplish having a large and small span to be centered (using line-height)? (and why is this behavior happening in the first place?)

.header {
    background: grey;
    width: 100%;
    height: 65px;
}

.big, .small {
    line-height: 65px;
}

.big {
    font-size: 1.5em;
}

.

<div class="header">
 <span class="big">A</span>
 <span class="small">B</span>
</div>
<br/>
<div class="header">
 <span class="small">A</span>
 <span class="small">B</span>
</div>
<br/>
<div class="header">
 <span class="big">A</span>
 <span class="big">B</span>
</div>

JS Fiddle Example


Solution

  • This happens, because default vertical-align is baseline. If you switch it to vertical-align:middle you get the expected behaviour.

    Edit for clarification: As span's are inline elements they share the same baseline, regardless of the font size you are using. Vertical alignment of text is baseline initially, but by setting it to middle, you force these inline elements to align vertically centered.

    More info on vertical align here: https://developer.mozilla.org/en/docs/Web/CSS/vertical-align