Flexbox space-between but center if one element

dhr*_*hrm 5 css flexbox

I've the following HTML and CSS.

<div class="container-box">
  <div class="box"></div>
  <div class="box"></div>
</div>
<div class="container-box">
  <div class="box"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)

Which gives this layout:

CSS布局

The first layout for multiple items does what I expect, but how can I change the second to position the element in center as it only has one element?

See this codepen: https://codepen.io/dennismadsen/pen/oNvqjjV

Mic*_*l_B 5

For cases where you have one item in the container, you can use the :only-child pseudo-class.

Add this to your code:

.box:only-child {
  margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)

.box:only-child {
  margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)

In such cases, flex auto margins will override justify-content because:

§ 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.


More about :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.


More about flex auto margins:


Also, to spotlight some interesting flex behavior, if you were using space-around instead of space-between, you wouldn't need auto margins.

  • 如果容器中存在通过“display: none”隐藏的元素,则此方法不起作用 (2认同)