2016-11-24 70 views
5

我正在嘗試在頁面中間放置一個紅色方塊。爲什麼我的柔性物品不在中心對齊?

我已經柔性容器設置爲100%的高度,並且也設置了HTML,身體100%,它仍然不居中對齊。

誰能請幫助我理解爲什麼它不工作?謝謝!

html, body { 
 
    height: 100%; 
 
} 
 
.flex-container { 
 
    display: flex; 
 
    flex-flow: column; 
 
    justify-content: center; 
 
    height: 100%; 
 
} 
 
.box { 
 
    flex: 0 0 100px; 
 
    background: red; 
 
    width: 100px; 
 
}
<div class='flex-container'> 
 
    <div class='box'></div> 
 
</div>

回答

4

您使用justify-content對齊的主軸彎曲的物品。

您可以使用align-items來對齊交叉軸上的彈性項目。

由於您的柔性容器是flex-direction: column

  • 主軸線是垂直的,並且
  • 橫軸是水平的。

justify-content: center工作正常。

你只需要添加align-items: center

html, body { 
 
    height: 100%; 
 
} 
 
.flex-container { 
 
    display: flex; 
 
    flex-flow: column; 
 
    justify-content: center;  /* centers flex items vertically, in this case */ 
 
    align-items: center; /* NEW */ /* centers flex items horizontally, in this case */ 
 
    height: 100% 
 
} 
 
.box { 
 
    flex: 0 0 100px; 
 
    background: red; 
 
    width: 100px; 
 
}
<div class='flex-container'> 
 
    <div class='box'></div> 
 
</div>

這裏有一個更詳細的解釋:

+1

謝謝!這對我有效! – json1