2017-04-19 51 views

回答

2

您可以在第一个和最后一个子div上添加margin-top: auto。当您将margin-top: auto添加到last-child div时,它会将该div推到父代的结尾,但它也会将其他两个div推到父代的顶端。这就是为什么你还需要将margin-top: auto添加到第一个孩子的div,并且这将把他们放置在从顶部到最后一个孩子div的空间中心。

.container { 
 
    display: flex; 
 
    flex-direction: column; 
 
    align-items: center; 
 
    justify-content: center; 
 
    min-height: 100vh; 
 
} 
 
.container div { 
 
    margin: 5px; 
 
    padding: 5px 10px; 
 
    border: 1px solid; 
 
} 
 
.container > div:last-child, 
 
.container > div:first-child{ 
 
    margin-top: auto; 
 
}
<div class="container"> 
 
    <div>This div should be vertically centered</div> 
 
    <div>This one too</div> 
 
    <div>And this div shoud be placed at the bottom of the flex container</div> 
 
</div>

+0

谢谢!这个对我有用。 – Byteshifter