如何使用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>





http://codepen.io/anon/pen/zLxBo

最佳答案

我认为您想要以下内容。



html, body {
    height: 100%;
}
body {
    margin: 0;
}
.flex-container {
    height: 100%;
    padding: 0;
    margin: 0;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    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元素应为块级(div而不是span)。

另外,在.row上,将宽度设置为auto而不是100%

您的.flex-container属性很好。

如果希望.row在视口中垂直居中,请为htmlbody分配100%的高度,并且将body边距清零。

请注意,.flex-container需要一个高度才能看到垂直对齐效果,否则,容器将计算包围内容所需的最小高度,该最小高度小于此示例中的视口高度。

脚注:
flex-flowflex-directionflex-wrap属性可以使此设计更易于实现。我认为除非您要在元素周围添加一些样式(背景图像,边框等),否则不需要.row容器。

有用的资源是:http://demo.agektmr.com/flexbox/

10-08 13:24
查看更多