我在容器中有一堆div,我想要水平均匀分布:
[container [obj1] [obj2] [obj3] [obj4] ]
但我也希望容器在页面中居中
现在我的容器的css(手写笔)代码如下:
@media( min-width: 900px ) {
display: flex;
width: 830px;
margin 0 auto;
justify-content: space-between;
}
导致一些奇怪的边距并且容器没有在页面中居中。这是因为我使用display:flex
和'justify-content`字段的方式?
答案 0 :(得分:1)
如果您想要.container
居中,可以再次在其父级上添加display: flex
,并使用align-items: center
和justify-content: center
将容器置于中心位置,如下所示:
body {
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
margin: 0;
padding: 0;
background: yellow;
}
.container {
display: flex;
border: 1px solid;
width: 70%;
height: 20%;
align-items: center;
justify-content: space-between;
}
.child {
background: red;
border: 1px solid;
padding: 6px;
margin: 0 6px;
}

<div class="container">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
</div>
&#13;
答案 1 :(得分:1)
使用450px
容器获取以下示例。正如您所建议的那样,正确使用justify-content:space-between
可以在div
元素之间提供均匀的间距。
.container {
display: flex;
width: 450px;
height: 50px;
margin: 0 auto;
padding: 2px;
border: 1px solid black;
justify-content:space-between;
}
.container div {
border: 1px solid red;
margin: 4px;
}
<div class="container">
<div>1</div>
<div>small</div>
<div>very large content</div>
</div>
现在,假设您希望扩展每个div
以占用所有剩余空间,并使div
元素均匀分布。在子flex-grow:1
元素上使用div
可以占用剩余空间。添加width:calc(100%/3)
以均匀调整大小。
.container {
display: flex;
width: 450px;
height: 50px;
margin: 0 auto;
padding: 2px;
border: 1px solid black;
justify-content:space-between;
}
.container div {
border: 1px solid red;
margin: 4px;
flex-grow:1;
width:calc(100%/3);
}
<div class="container">
<div>1</div>
<div>small</div>
<div>very large content</div>
</div>
最后,要在媒体查询中完成该工作,您需要按如下方式调整您的CSS:
@media( min-width: 450px) {
.container {
display: flex;
width: 400px;
margin: 0 auto;
justify-content: space-between;
}
.container div {
border: 1px solid red;
margin: 4px;
flex-grow: 1;
width: calc(100%/3);
}
}
<div class="container">
<div>1</div>
<div>small</div>
<div>very large content</div>
</div>