2017-04-19 50 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