I'm messing around with everyone's favorite CSS topic, vertical alignment. I found a little case that makes no sense to me, which probably means I'm failing to understand something about CSS.
I have the following HTML (it's for exploration code, so please excuse the inline styles):
<div style="height: 40px; line-height: 40px; vertical-align: middle; border: 1px solid blue; margin: 1em 2em;">
<span style="background-color: Blue; height: 30px; width: 30px; margin: 5px 1em; display:inline-block;"> </span>
<span>Some text</span>
</div>
This displays a blue box and some text, both vertically centered. But if I replace the
with a regular space character, the text in the other span is no longer centered. I created a JSFiddle that demonstrates this.
My question is - why does changing from an
to a space character in the first span change the vertical alignment of the second span?
You are confused how the vertical-align
property works. It doesn't apply to block-level elements. When it is set on a non-table-cell and non-inline element, the property is actually applied to all the inline text inside that element, not to the element itself.
When you use a regular space, the space isn't actually "rendered" by the browser because it's not really content. Therefore, the entire box becomes the line of text (since you're displaying it as inline-block) and the baseline is set at the very bottom of the parent against the black border at the bottom, which is why the text appears way down there.
When you use a non-breaking space, the space is content and does get render, which moves the baseline for the text up to where the text would actually appear inside the blue box. It's not actually centering the text. It's nowhere near centered on my screen. The baseline has just moved based on the content. You'll notice from this example that it also changes the line-height of the continuing text.
An easy way to fix this is to float the blue box to the left and then manually set a line-height for the rest of the text to follow. See the jsFiddle.
<div style="height: 40px; line-height: 40px; vertical-align: middle; border: 1px solid blue; margin: 1em 2em;">
<span style="background-color: Blue; height: 30px; width: 30px; margin: 5px 1em; float: left;"></span>
<span>Some text that continues on and on and on sothat you can see what is actually happening here blah blah blah blah blah</span>
</div>
The entity
stands for non breaking space and is a variant of the space char.
They aren't the same.
In fact the entity prevents an automatic line break
Read more about at wikipedia
Moreover, the white space result as an "empty" span and that will cause that "bad behaviour"
May help?:
http://jsfiddle.net/mFryV/18/