简体   繁体   English

在弹性项目中垂直和水平居中文本

[英]Centering text vertically and horizontally in a flex item

I was trying to follow along the flexbox example and my line-height is not working for this problem. 我试图跟随flexbox示例,我的行高不适用于此问题。

The text should be vertically centered, but it's not. 文本应该是垂直居中的,但事实并非如此。 It remains at the top only horizontally centered. 它仅保持在水平居中的顶部。

In the code snippet it seems to work fine but just to prove that this is acting strange I will give a picture of what I am seeing. 在代码片段中它似乎工作正常,但只是为了证明这是行为奇怪我会给出我所看到的图片。

I tested this in both Chrome and IE but it's not vertically centering. 我在Chrome和IE中测试了这个,但它没有垂直居中。

I did change the sizes in the snippet, but I don't think that'd do it. 我确实改变了片段中的大小,但我认为不会这样做。

在此输入图像描述

 .flex-container { display: flex; flex-flow: row wrap; justify-content: space-around; padding: 0; margin: 0; list-style: none; display: -webkit-box; display: moz-box; display: -ms-flexbox; display: -webkit-flex; -webkit-flex-flow: row wrap; } .flex-item { background: tomato; padding: 5px; width: 50px; height: 50px; margin-top: 10px line-height: 50px; color: white; font-weight: bold; font-size: 3em; text-align: center; } 
 <ul class="flex-container"> <li class="flex-item">1</li> <li class="flex-item">2</li> <li class="flex-item">3</li> <li class="flex-item">4</li> <li class="flex-item">5</li> <li class="flex-item">6</li> </ul> 

To vertically and horizontally center the text in each flex item, make this adjustment to your code: 要在每个弹性项目中垂直和水平居中文本,请对您的代码进行此调整:

 .flex-container { display: flex; flex-flow: row wrap; justify-content: space-around; padding: 0; margin: 0; list-style: none; display: -webkit-box; display: moz-box; display: -ms-flexbox; display: -webkit-flex; -webkit-flex-flow: row wrap; } .flex-item { display: flex; /* create nested flex container */ justify-content: center; /* center text horizontally */ align-items: center; /* center text vertically */ background: tomato; padding: 5px; width: 50px; height: 50px; color: white; font-weight: bold; font-size: 3em; } 
 <ul class="flex-container"> <li class="flex-item">1</li> <li class="flex-item">2</li> <li class="flex-item">3</li> <li class="flex-item">4</li> <li class="flex-item">5</li> <li class="flex-item">6</li> </ul> 

For more details see: Flexbox: center horizontally and vertically 有关详细信息,请参阅: Flexbox:水平和垂直居中

You missed a ";" 你错过了一个“;” after margin-top in flex-item, which make the line-height inactive 在flex-item中的margin-top之后,这使得行高无效

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

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