Why this trick centers text vertically in dynamic height div (and why it breaks)?

Viewed 504

I found this stackoverflow answer very interesting. It works to vertically center text of any length in a div of any height. Basically it uses a empty <span> tag directly in front of the node containing text, and

HTML:

<div>
    <span></span><p>This is really really long text but it will be centered vertically.</p>
</div>​

CSS:

div { 
    background: yellow; 
    color: red;
    width: 200px;
    text-align: center; /* horizontally center */
    height: 300px; /* any height */
    padding: 0 20px
}

div span:first-child {
    height: 100%;
    vertical-align: middle;
    display: inline-block; 
}

div p {
    margin: 0;        
    vertical-align: middle;
    display: inline-block; 
}

Also even more interesting is if you separate closing span tag (</span>) and opening paragraph tag (<p>) on two separate lines, or if you add a whitespace between the two, the trick breaks.

My question is - how does this trick work? How is span helping center the text? And why does it break when a newline/whitespace is added in HTML between closing </span> tag and opening <p> tag?

I have created a fiddle to demonstrate both points: https://jsfiddle.net/axRxE/385/

1 Answers
Related