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
How to center align a flexbox container?
提问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:auto
but 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>
回答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;
}
}
回答by Alaa DAIRY
just add this line to your original code:
只需将此行添加到您的原始代码中:
.container{
width: 100%
}
and put the div
box into another div
that have a margin: auto;
然后把div
盒子放到另一个div
有margin: auto;
if you need 2 boxes in the same line add display: inline-table;
to the box
class
如果您需要在同一行中添加 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;
}