且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CSS垂直对齐 - 我不理解什么?

更新时间:2022-10-17 19:17:13

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>​

相关阅读

技术问答最新文章