簡體   English   中英

在div中垂直居中放置文本:display:flex和align-items:center不起作用

[英]Vertically center text in div: display:flex and align-items:center not working

目標是在div中垂直居中放置文本。 該答案建議使用display: flexalign-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM