简体   繁体   English

如何垂直对齐文本?

[英]How to vertical align a text?

How to vertically align the text in a floated div? 如何在浮动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 谢谢

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). Javascript是一种替代方法(测量div的大小和文本大小,然后调整padding或lineheight或其他任何值)。

edit: Or this awesome css: 编辑:或这真棒css:

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 的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. 一段时间以来,我一直想写一篇关于这个的博客文章,我想是时候了。

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. 乐观地说,任何用于垂直对齐的跨浏览器CSS解决方案都将很难维护两倍。

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

Chris Coyier wrote an excellent tutorial on just this: http://css-tricks.com/vertically-center-multi-lined-text/ 克里斯·科耶尔(Chris Coyier)为此撰写了出色的教程: http : //css-tricks.com/vertically-center-multi-lined-text/

I've used it myself, and it works perfectly. 我自己使用过,效果很好。

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... 这是我的第一个答案...

Have you tried vertical-align: middle; 您是否尝试过垂直对齐:中间; ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM