2016-06-26 79 views
3

我正在嘗試沿着flexbox示例行,並且我的行高無法解決此問題。在flex項中垂直和水平居中文本

該文本應該垂直居中,但事實並非如此。它仍然處於頂部,只能水平居中。

在代碼片段中,它似乎工作正常,但只是爲了證明這是行爲奇怪,我會給我看到的圖片。

我在Chrome和IE中都測試過它,但它不是垂直居中。

我確實改變了代碼片段的大小,但我認爲不會這樣做。

enter image description here

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

+2

關閉'的margin-top:10px' – Erevald

+0

對不起.... 我想要的文字進行垂直和水平居中:/ 我只是試圖使用行高來實現 但其他人已經回答了 –

+0

@ Shinji-san,它是否必須以「line-height」爲中心?由於您使用的是flexbox,因此可以縱向和橫向居中。 –

回答

2

要垂直和水平居中在每個柔性項中的文本,使這個調整你的代碼:

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

欲瞭解更多詳情請參閱:Flexbox: center horizontally and vertically

0

您錯過了「;」後邊距在柔性項,使行高不活躍