css - Flexbox space-between but center if one element

标签 css flexbox

我有以下 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;
}

这给出了这个布局:

CSS layout

多个元素的第一个布局符合我的预期,但我如何更改第二个以将元素定位在中心,因为它只有一个元素?

请参阅此代码笔:https://codepen.io/dennismadsen/pen/oNvqjjV

最佳答案

对于容器中只有一项的情况,可以使用 :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 margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.


关于 :only-child 的更多信息:

§ 6.6.5.10. :only-child pseudo-class

The :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/

相关文章:

css - 嵌套的 flexboxes : IE11 doesn't respect max-width: 100%

jquery - 更改单个div的高度(Flexbox)

css - Flexbox:试图在段落元素之上获取 H1 元素

css - flexbox 垂直拆分容器为 HALF

html - flex-box,保持第一行展开

css - 如何删除 Firefox 在按钮和链接上的虚线轮廓?

css - Magnific PopUp - 自定义标题 Css

Jquery 回调函数没有改变 css 属性

html - 如何让页面并排的2个DIV内容独立向下或向上滚动而不使用框架?

jquery - 无法居中淡入淡出图像 (jQuery)