【问题标题】:Why isn't my flex item aligning in the center?为什么我的弹性项目没有在中心对齐?
【发布时间】:2017-04-08 04:16:11
【问题描述】:
我正在尝试在页面中间居中放置一个红色框。
我已将 flex 容器的高度设置为 100%,并将 html,body 设置为 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>
【问题讨论】:
标签:
html
css
flexbox
centering
【解决方案1】:
您使用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>
这里有更详细的解释: