将项目对齐到中心但保持属性之间的空间

问题描述

我需要知道如何在保持 justify-content: space-between 属性的同时将元素置于中心位置?

大概是这样的:

enter image description here

红色项目需要与 justify-content: space-between 对齐,以便它们“接触”黑线。如果该行上只有一项,则它会居中对齐。

解决方法

您可以使用 flex-basis: calc(50% - x) 其中 x 是同一行中每两个元素之间距离的一半,然后在最后一个元素上使用 margin:auto 如果它是该行中的唯一元素(即如果它是最后一个元素并且具有奇数顺序)。我正在使用 20px auto 0px auto 以便我不会覆盖我在之前的规则中设置的上边距。

.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.flex div {
  flex-basis: calc(50% - 50px);
  height: 100px;
  margin-top: 50px;
  background: #D85E5E;
}

.flex div:last-child:nth-child(odd) {
  margin: 50px auto 0px auto;
}
<div class="flex">
  <div></div>
  <div></div>
  <div></div>
</div>

,

.flexbox {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.flex-item {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin:20px 0;
}  


.item {
  height: 75px;
  width: 150px;
  background-color: pink;
}

.item:only-child {
  margin: 0 auto;
}
<div class="flexbox">
  <div class="flex-item">
    <div class="item"></div>
    <div class="item"></div>
  </div>
  <div class="flex-item">
    <div class="item"></div>
  </div>
</div>