How to vertical align a text?

社会主义新天地 提交于 2019-11-29 02:46:59

问题


How to vertically align the text in a floated div? For example: I have a dynamic content with fixed height. if the content is small or big it has to automatically vertically align.

Thanks


回答1:


Table cells are the easiest solution.

Javascript is an alternative (measure the size and text size of the div, then adjust padding, or lineheight, or whatever).

edit: Or this awesome css:

CSS

div#container {
    border: solid 1px;
    height: 300px;
}

div#content {
    border: solid 1px;
}

div#balance {
    border: solid 1px;
    /* gotta be 100% */
    height: 100%;
}

div.valign {
    /* firefox 2 */
    display: -moz-inline-box;
    /* everybody else */
    display: inline-block;

    vertical-align: middle;
}

/* IE 6 and 7 hack */
html* div.valign {
    display: inline;
}

HTML

<div id="container">
    <div id="balance" class="valign"></div>
    <div id="content" class="valign">
        Blah blah blah blah<br/>
        Blah blah blah blah<br/>
        Blah blah blah blah<br/>
        Blah blah blah blah<br/>
        Blah blah blah blah
    </div>
</div>

Been meaning to make a blog post about this for a while, I think it's time.




回答2:


I know this is going to ruin my reputation, but ... use a table cell. Any cross-browser CSS solution for vertical alignment will be twice as difficult to maintain, being optimistic.




回答3:


<div style="display: table-cell; vertical-align: middle;">I'm in the middle!</div>



回答4:


Chris Coyier wrote an excellent tutorial on just this: http://css-tricks.com/vertically-center-multi-lined-text/

I've used it myself, and it works perfectly.




回答5:


I've come across this problem before. I'll quote the experts so I don't fudge this up: "...internal object is absolutely positioned in half of the area height. Then is moved up by half of its height."

This can be all done with % instead of exact pixels, in case the data is generated from a database and the height varies with each page.

Source: here

Demo: linked on the above page

Here goes my first answer...




回答6:


Have you tried vertical-align: middle; ?



来源:https://stackoverflow.com/questions/1101827/how-to-vertical-align-a-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!