如何居中对齐flexbox容器?

时间:2016-08-11 12:12:06

标签: html css html5 alignment flexbox

我在代码段显示时成功创建了一个响应式网格。

此刻,我看到方框左侧对齐。

如何在不使用填充的情况下将容器放在页面的中心?

我尝试使用margin:auto,但它没有用。

.container{
    display:flex;
    flex-wrap:wrap;
    text-align:center;
    margin:auto;
}
.box{
    width:100%;
    max-width:30%;
    border:1px solid red;
    margin:5px;
}
@media only screen and ( max-width:768px ){	
    .box{
        width:100%;
        max-width:40%;
        border:1px solid red;
    }
}
<section class="container">
    <div class="box">
        <h1>This is the first box</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci voluptates, aut totam eaque possimus molestiae atque odio vero optio porro magni, quis culpa ea. Perferendis, neque, enim. Rem, quia, quisquam.</p>
    </div>
</section>

JS Fiddle

4 个答案:

答案 0 :(得分:10)

使用justify-content: center;代替margin: auto;

.container {
  display: flex;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
}
.box {
   width: 100%;
   max-width: 30%;
   border: 1px solid red;
   margin: 5px;
}
@media only screen and (max-width: 768px) { 
  .box {
    width: 100%;
    max-width: 40%;
    border: 1px solid red;
  }
}

请参阅justifiy-content docs on MDN

Updated JS Fiddle.

答案 1 :(得分:0)

只需将此行添加到原始代码中:

.container{
  width: 100%
}

并将div框放入另一个div

margin: auto;

如果您需要在同一行中添加2个框,请将display: inline-table;添加到box

答案 2 :(得分:0)

width.container{ display:flex; flex-wrap:wrap; text-align:center; margin:0px auto; width: 400px; } 一起使用。

例如:

namespace System.Runtime.CompilerServices {
    sealed class CallerMemberNameAttribute : Attribute { }
}

答案 3 :(得分:0)

所以,如果你想从左到右添加方框,并且下一行的第一个方框要左对齐,你可以使用:`

.container {
  display:flex;
  flex-flow: row wrap;
  justify-content: flex-start;
  margin: 0 auto;
  border: 1px solid red;
}
.container:after {
  content: "";
  flex: auto;
}

Fiddle

相关问题