如何使用 flexbox 在容器内水平和垂直居中 div。在下面的示例中,我希望每个数字彼此下方(按行),水平居中。
.flex-container {
padding: 0;
margin: 0;
list-style: none;
display: flex;
align-items: center;
justify-content: center;
}
row {
width: 100%;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
}
<div class="flex-container">
<div class="row">
<span class="flex-item">1</span>
</div>
<div class="row">
<span class="flex-item">2</span>
</div>
<div class="row">
<span class="flex-item">3</span>
</div>
<div class="row">
<span class="flex-item">4</span>
</div>
</div>
最佳答案
我想你想要像下面这样的东西。
html, body {
height: 100%;
}
body {
margin: 0;
}
.flex-container {
height: 100%;
padding: 0;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
}
.row {
width: auto;
border: 1px solid blue;
}
.flex-item {
background-color: tomato;
padding: 5px;
width: 20px;
height: 20px;
margin: 10px;
line-height: 20px;
color: white;
font-weight: bold;
font-size: 2em;
text-align: center;
}
<div class="flex-container">
<div class="row">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
<div class="flex-item">4</div>
</div>
</div>
参见演示:http://jsfiddle.net/audetwebdesign/tFscL/
如果你想要高度和顶部/底部填充,你的 .flex-item
元素应该是 block 级的(div
而不是 span
)才能正常工作。
此外,在 .row
上,将宽度设置为 auto
而不是 100%
。
您的 .flex-container
属性没问题。
如果您希望 .row
在视口(viewport)中垂直居中,请将 100% 高度分配给 html
和 body
,并且将 body
边距清零。
注意.flex-container
需要一个高度才能看到垂直对齐效果,否则容器会计算围住内容需要的最小高度,这个高度小于视口(viewport)高度示例。
脚注:
flex-flow
、flex-direction
、flex-wrap
属性可以使此设计更易于实现。我认为不需要 .row
容器,除非您想在元素周围添加一些样式(背景图像、边框等)。
关于html - Flexbox:水平和垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35682498/