2016-01-05 61 views
2

我有一個彈性容器.container和兩個彈性項目:item-oneitem-two。我想垂直居中第一項並將第二項固定在底部。垂直對齊兩個彈性項目

我不知道如何垂直對齊此上下文中的第一項。

HTML:

<div class="container"> 
    <div class="item-one">Item One</div> 
    <div class="item-two">Item Two</div> 
</div> 

CSS:

html, body { 
    height: 100%; 
    margin: 0; 
} 

.container { 
    width: 500px; 
    margin: 0 auto; 
    border: 5px solid orange; 
    height: 100%; 

    /* Flex properties */ 
    display: flex; 
    flex-wrap: wrap; 
    align-items: center; 
    justify-content: center; 
} 

.item-one { 
    border: 5px solid yellow; 
    flex-basis: 500px;  
} 

.item-two { 
    border: 5px solid red; 
    align-self: flex-end; 
} 

CodePen

回答

0

你可以使用auto margins對準這樣的元素。這將允許您向auto保證金的方向分配任何積極的可用空間。

在這種情況下,您需要將flex-direction更改爲column,以使Flexbox項目垂直流動。然後,您可以在第一個柔性盒項目上設置margin-top: auto/margin-bottom: auto以便垂直居中並確保其上下的空間相等。在此過程中,這將第二個項目推到了底:

Updated Example

html, body { 
 
    height: 100%; 
 
    margin: 0; 
 
} 
 
.container { 
 
    width: 500px; 
 
    margin: 0 auto; 
 
    border: 5px solid orange; 
 
    height: 100%; 
 
    display: flex; 
 
    flex-direction: column 
 
} 
 
.item-one { 
 
    border: 5px solid yellow; 
 
    margin: auto 0; 
 
} 
 
.item-two { 
 
    border: 5px solid red; 
 
    margin: 0 auto; 
 
}
<div class="container"> 
 
    <div class="item-one">Item One</div> 
 
    <div class="item-two">Item Two</div> 
 
</div>