如何在flex元素中垂直居中文本? [英] How do I vertically center the text within a flex element?

查看:783
本文介绍了如何在flex元素中垂直居中文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有特殊的方法使用flexbox(或其他纯CSS)在一个元素中垂直居中文本?

Is there a special way to vertically center text in an element using flexboxes (or other pure CSS)?

小提琴: http://jsfiddle.net/WK_of_Angmar/JZZWg/

<body>
<div id="main">
    <section id="a">Test1</section>
    <section id="b">Test2</section>
</div>

#a {
    flex: 1 0 auto;
}
#b {
    flex: 0 0 auto;
    min-height: 3em;
    background-color: yellow;
}
#a {
    background-color: blue;
}
#main {
    display: flex;
    flex-direction: column;
    height: inherit;
}

body {height: inherit;}
html {height: 100%;}


推荐答案

使用 line-height 是一个解决方案,这里是 链接 到小提琴。

Using line-height is one solution, here's the link to Fiddle.

更新: strong>我对flex模型有一点兴趣,发现了对中属性,所以我想这为你做一个更好的解决方案(虽然不是那么整洁,优雅,因为所有的prfixes)。这是 链接 使用flex属性进行对齐。

Update: I took a little more interest in the flex model and found the centering properties, so I guess this makes a better solution for you (although not that neat and elegant because of all the prfixes). Here is the link to Fiddle using flex properties for alignment.

这里是 链接 ,解释属性的用法。

And here is a link that explains the usage of the properties.

这篇关于如何在flex元素中垂直居中文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆