How to center-align one flex item and right-align another using Flexbox [duplicate]

Using justify-content: space-between with an invisible flex item, as described in your question, is a good way to achieve the layout you want. Just note that the middle item can only be centered if both left and right items are equal length (see demo).

Another solution you may want to consider involves auto margins and absolute positioning. Two benefits of this method are no need for extra mark-up and true centering can be achieved regardless item sizes. One drawback is that the centered item is removed from the document flow (which may or may not matter to you).

.flexcontainer {
  display: flex;
  justify-content: flex-start;
  /* adjustment */
  position: relative;
  /* new */
  width: 500px;
  height: 200px;
}

.itemcenter {
  flex: 0 1 auto;
  width: 150px;
  height: 100px;
  position: absolute;
  /* new */
  left: 50%;
  transform: translateX(-50%);
}

.itemright {
  flex: 0 1 auto;
  width: 100px;
  height: 100px;
  margin-left: auto;
  /* new */
}
<div class="flexcontainer">
  <div class="itemcenter">One</div>
  <div class="itemright">Other</div>
</div>

More details here: Methods for Aligning Flex Items along the Main Axis (see boxes #62-78).

Leave a Comment