我正在尝试将一组包裹的弹性项目居中。 HTML看起来像这样:
main {
background-color: blue;
width: 390px;
display: flex;
justify-content: center;
}
.container {
background-color: red;
display: inline-flex;
flex-wrap: wrap;
}
.a1 {
color: grey;
width: 100px;
height: 200px;
background-color: green;
border: 1px solid black;
}
<main>
<div class="container">
<div class="a1"></div>
<div class="a1"></div>
<div class="a1"></div>
<div class="a1"></div>
</div>
</main>
以上看起来像这样:
绿色框被正确包裹,但它们整体上不在红色区域的中心,
没有在.container
上定义宽度,因为红色块可以有任何大小,我希望尽可能多地匹配彼此相邻的块。
有关如何将包裹的绿色区块居中的任何建议吗?
更新:根据this 2岁的帖子,这是不可能的。所以在我的情况下,我必须使用JavaScript来解决这个问题。但也许我可以使用CSS Grid Layout
答案 0 :(得分:9)
不确定你想要什么样的居中
所以有几个选择:
.container
justify-content: center;
添加到.container
而不是
main {
background-color: blue;
width: 390px;
display: flex;
}
.container {
background-color: red;
display: flex;
flex-wrap: wrap;
justify-content:center;
}
.a1 {
color: grey;
width: 100px;
height: 200px;
background-color: green;
border: 1px solid black;
}
<main>
<div class="container">
<div class="a1"></div>
<div class="a1"></div>
<div class="a1"></div>
<div class="a1"></div>
</div>
</main>
.container
width
+ margin:auto
添加到.container
main {
background-color: blue;
width: 390px;
display: flex;
justify-content: center;
}
.container {
background-color: red;
display: inline-flex;
flex-wrap: wrap;
width: 300px;
margin: auto;
}
.a1 {
color: grey;
width: 100px;
height: 200px;
background-color: green;
border: 1px solid black;
box-sizing: border-box
}
<main>
<div class="container">
<div class="a1"></div>
<div class="a1"></div>
<div class="a1"></div>
<div class="a1"></div>
</div>
</main>
main {
background-color: blue;
width: 390px;
display: flex;
}
.container {
background-color: red;
display: inline-flex;
flex-wrap: wrap;
width: 90%;
margin: auto;
justify-content: center;
}
.a1 {
color: grey;
width: 100px;
height: 200px;
background-color: green;
border: 1px solid black;
}
<main>
<div class="container">
<div class="a1"></div>
<div class="a1"></div>
<div class="a1"></div>
<div class="a1"></div>
</div>
</main>
答案 1 :(得分:1)
如果你只是想让容器居中,给容器一个固定的宽度,或者确保容器的宽度具有预期的宽度。
main {
background-color: blue;
width: 390px;
display: flex;
justify-content: center;
}
.container {
background-color: red;
display: inline-flex;
flex-wrap: wrap;
width:306px;
}
.a1 {
color: grey;
width: 100px;
height: 200px;
background-color: green;
border: 1px solid black;
}
<main>
<div class="container">
<div class="a1"></div>
<div class="a1"></div>
<div class="a1"></div>
<div class="a1"></div>
</div>
</main>