Blu Blu - 5 months ago 14
CSS Question

CSS Flexbox space-between: Keep one element in center

I am making a music playback controller, and the container has 3 sections: left, center, and right. However, since the left and right sides have different widths, the center section isn't in the true center of the div, but I need it to be. I am using flexbox's

space-between
option to layout the items.



#container {
display: flex;
justify-content: space-between;
background-color: lightgrey;
}

#container > div {
height: 100px;
border: 2px dashed red;

/*This is only for looks*/
text-align: center;
padding: 5px;
}

<div id="container">
<div>Left Side</div>
<div>I want this centered</div>
<div>Right Side (Extra text for extra length)</div>
</div>




Answer

If you want an absolute centered div, which will eliminate any space between the right and center divs, you will need to specifically target the center div with a margin-left declaration of auto. Using margin in conjunction with flexbox allows you to push an item to a side of a container or center it.

#container {
    display: flex;
    justify-content: space-between;
    background-color: lightgrey;
}

#container > div {
  height: 100px;
  border: 2px dashed red;
  
  /*This is only for looks*/
  text-align: center;
  padding: 5px;
}
.center {
margin-left: auto;
}
<div id="container">
  <div class="left">Left Side</div>
  <div class="center">I want this centered</div>
  <div class="right">Right Side (Extra text for extra length)</div>
</div>

You could also change #container's justify-content value to flex-end and target the first child div with a margin-right declaration of auto. If you aren't actually having space between all the divs, that may make more sense semantically.