2016-01-05 59 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>