![](/img/trans.png)
[英]Using flex align-items center to vertically center text inside div
[英]Vertically center text in div: display:flex and align-items:center not working
目标是在div中垂直居中放置文本。 该答案建议使用display: flex
和align-items: center
,但是不起作用。
Codepen: https ://codepen.io/anon/pen/qgOJZg
<div id="messageBox" style="">
<div class="message">YO THERE THIS ROCKS!</div>
</div>
#messageBox {
min-width: 150px;
padding: 15px 35px;
position: absolute;
margin-left: 50%;
bottom: 0;
background: #424242;
color: #FFF;
cursor: pointer;
text-align: center;
border-radius: 5px 5px 0 0;
font-family: "Lato";
font-size: 17px;
display: flex;
align-items: center;
justify-content: center;
}
有太多的解释。 但是现在,只看一下更新的小提琴 。
首先,您的容器的内容高度即文本框,仅此而已,因此文本框基本上位于其容器的中心。 但是,当您给它一个height
,您会发现它不在中心。 由于flex-box的性质,它具有flex-direction: row
默认为flex-direction: row
。 因此,您要将其更改为column
(这是我在提供的jsFiddle中所做的事情),仅此而已。
CSS的结构也进行了一些适度的更改,但是您会发现自己“自言自语”; 无需解释。
作为进一步的调查, position: absolute
将使孩子脱离flex-flow
就像它根本不是后代一样。 使用flex-box
,大多数时候不需要绝对定位的元素。
同样,作为进一步的阅读,请在css-tricks.com上查看有关flex-box
精彩文章 ; 涵盖了所有内容,并且超级简单易学。
只需将您的#messageBox设置为此
#messageBox {
display: flex;
justify-content: center;
flex-direction: column;
text-align: center;
}
实时示例: https : //codepen.io/anon/pen/VgvEyY
@Crashalot:通过使用高度,我们可以实现,但是您也可以通过使用此代码在垂直方向上居中。
#messageBox { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .message { position: relative; min-width: 150px; padding: 15px 35px; background: #424242; color: #FFF; cursor: pointer; cursor: pointer; text-align: center; border-radius: 5px 5px 0 0; font-family: "Lato"; font-size: 17px; }
<div id="messageBox" style=""> <div class="message">YO THERE THIS ROCKS!</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.