2016-11-24 48 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

相关问题