Html 如何居中对齐 flexbox 容器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38896055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:41:20  来源:igfitidea点击:

How to center align a flexbox container?

csshtmlalignmentflexbox

提问by user agent

I successfully created a responsive grid as the snippet shows.

如代码段所示,我成功创建了一个响应式网格。

At the moment, I see the boxes aligned to the left.

目前,我看到框与左侧对齐。

How can I put the container in the center of the page without having to use padding?

如何将容器放在页面中央而不必使用填充?

I tried using margin:autobut it did not work.

我尝试使用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.

JS小提琴

回答by Micha? Per?akowski

Use justify-content: center;instead of margin: auto;:

使用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;
  }
}

See justifiy-contentdocs on MDN.

请参阅justifiy-contentMDN 上的文档

Updated JS Fiddle.

更新了 JS 小提琴。

回答by Alaa DAIRY

just add this line to your original code:

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

.container{
  width: 100%
}

and put the divbox into another divthat have a margin: auto;

然后把div盒子放到另一个divmargin: auto;

if you need 2 boxes in the same line add display: inline-table;to the boxclass

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

回答by 2dsharp

Use margin:0px auto;with a width.

使用margin:0px auto;width

For example:

例如:

.container{

display:flex;
flex-wrap:wrap;
text-align:center;
margin:0px auto;
width: 400px;
}

回答by Julsy

So, if you want to have boxes being added from left to right, and the first box on the next row to be left aligned, you can use:`

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

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

Fiddle

小提琴