我有以下 HTML 和 CSS。
<div class="container-box">
<div class="box"></div>
<div class="box"></div>
</div>
<div class="container-box">
<div class="box"></div>
</div>
.container-box {
width: 200px;
display: flex;
flex-direction: row;
justify-content: space-between;
background-color: red;
margin:50px;
}
.box {
background-color: #9009A0;
height: 50px;
width: 50px;
}
这给出了这个布局:
多个元素的第一个布局符合我的预期,但我如何更改第二个以将元素定位在中心,因为它只有一个元素?
最佳答案
对于容器中只有一项的情况,可以使用 :only-child
伪类。
将此添加到您的代码中:
.box:only-child {
margin: 0 auto;
}
.container-box {
width: 200px;
display: flex;
flex-direction: row;
justify-content: space-between;
background-color: red;
margin: 50px;
}
.box {
background-color: #9009A0;
height: 50px;
width: 50px;
}
.box:only-child {
margin: 0 auto;
}
<div class="container-box">
<div class="box"></div>
<div class="box"></div>
</div>
<div class="container-box">
<div class="box"></div>
</div>
在这种情况下,flex auto
边距将覆盖 justify-content
因为:
§ 8.1. Aligning with
auto
marginsPrior to alignment via
justify-content
andalign-self
, any positive free space is distributed to auto margins in that dimension.
关于 :only-child
的更多信息:
§ 6.6.5.10.
:only-child
pseudo-classThe
:only-child
pseudo-class represents an element that has no siblings. Same as:first-child:last-child
or:nth-child(1):nth-last-child(1)
, but with a lower specificity.
关于 flex auto
边距的更多信息:
此外,为了突出一些有趣的 flex 行为,如果您使用 space-around
而不是 space-between
,则不需要 auto
边距。
关于css - Flexbox space-between but center if one element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57859754/