Html 如何垂直对齐文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1101827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:11:32  来源:igfitidea点击:

How to vertical align a text?

csshtmlvertical-alignment

提问by Harry

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.

如何垂直对齐浮动div中的文本?例如:我有一个固定高度的动态内容。如果内容很小或很大,它必须自动垂直对齐。

Thanks

谢谢

回答by Ryan Florence

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 的大小和文本大小,然后调整填充、行高或其他任何内容)。

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.

有一段时间想写一篇关于这个的博客文章,我想是时候了。

回答by JerSchneid

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

回答by JerSchneid

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.

我自己用过,效果很好。

回答by GlenCrawford

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

这是我的第一个答案...

回答by whichdan

Have you tried vertical-align: middle; ?

您是否尝试过垂直对齐:中间;?