2016-09-30 153 views
3

我正在嘗試使用flexbox垂直對齊三個div塊。使用flexbox垂直對齊div

我可以讓它們水平對齊,但不是垂直。

我在做什麼錯?

.banner { 
 
    padding-top: 10px; 
 
    padding-bottom: 10px; 
 
    background-color: #01b9d5; 
 
    color: white; 
 
    height: 55px; 
 
} 
 
.banner-align { 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
    border: 1px solid green; 
 
} 
 
.banner-hero { 
 
    flex: 1; 
 
    align-self: center; 
 
    max-width: 50%; 
 
    border: 1px solid red; 
 
    text-align: center; 
 
    display: inline-block; 
 
} 
 
.banner-left { 
 
    align-self: flex-start; 
 
    flex: 1; 
 
    border: 1px solid green; 
 
    display: inline-block; 
 
} 
 
.banner-right { 
 
    align-self: flex-end; 
 
    flex: 1; 
 
    text-align: right; 
 
    border: 1px solid yellow; 
 
    display: inline-block; 
 
}
<div class="banner"> 
 
    <div class="container banner-align"> 
 
    <div class="banner-left"> 
 
     Left Block 
 
    </div> 
 
    <div class="banner-hero"> 
 
     <b>Title</b> 
 
    </div> 
 
    <div class="banner-right"> 
 
     Right block 
 
    </div> 
 
    </div> 
 
</div>

這裏是一個小提琴:https://jsfiddle.net/zqc1qfk1/1/

+1

這是因爲帶有'.banner-align'風格的容器只與他的物品一樣高並且堅持到頂部。舉例來說,「身高:100%」,他的物品將與自己的自我屬性對齊。 – michaPau

+1

你的意思是這樣的:[JSFiddle](https://jsfiddle.net/zqc1qfk1/4/) –

+1

@Hunter Turner,michaPau是的,這很容易。非常簡單的錯誤。感謝您指出。 –

回答

1

簡單地使容器wrap,並給每個柔性項width: 100%

.banner-align { 
    display: flex; 
    flex-wrap: wrap; 
} 

.banner-align > * { 
    flex: 0 0 100%; 
} 

現在每個柔性項目佔用了所有空間的行中,迫使其他元素,創造新行。

revised fiddle

3

你缺少柔性的flex-direction:column屬性。

默認情況下,任何柔性容器都有一個flex-direction: row &這就是它不水平移動&的原因。您需要明確指定。

Here is more about it

.banner-align { 
    display: flex; 
    align-items: center; 
    justify-content: center; 
    border:1px solid green; 
    flex-direction: column; 
} 

更新了Fiddle

+0

我認爲他正在嘗試使所有垂直居中的項目排成一行,而不是創建一列 –

1

align-items: center上你的Flex父垂直中心的一切。但是,對孩子使用align-self: [anything but center]將覆蓋此。

編輯:

哎呀,因爲別人指出的那樣,你沒有得到原小提琴的align-self影響,因爲父母的身高沒有設置,所以它是唯一的,因爲它需要的是一樣高遏制孩子。如果孩子們的身高不一樣,你會看到他們交錯。

如果您試圖讓它們都居中,您可以擺脫align-self屬性,並讓父母上的那個align-items: center執行此操作。如果你想讓他們交錯,你不需要父母上的那一個align-items: center