3

I have a layout with three elements in flexbox like so:

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

<div class="flex-container">
  <div class="flex-item"> computed width of 50px </div>
  <div class="flex-item plz-center"> computed width of 25px </div>
  <div class="flex-item"> computed width of 150px </div>
</div>

I'd like to center the middle item plz-center and have the other items stay on either side, like this image:

flex-end

They work fine in the flex row, but if the widths of the end items are different, the middle item doesn't stay centered. Am I better off making plz-center fixed?

Nick Tassone
  • 153
  • 1
  • 8

1 Answers1

5

A simple solution to this problem would be to give your first box margin-right:auto and your last box margin-left:auto, the flex-box will sort out the rest and calculate spacing for you.

A more complex solution that is often used by websites when building grid systems, would be to wrap each of these flex-items in another DIV that is also a flex-box. Then make these new flex-boxes equally share the width of the master wrapping flex-box (1/3 of the width to each). Then inside of each of these boxes you can position your elements as you need. Here's an example (I've left black borders around the new wrapping flex-boxes so you can better see how this behaves):

body {
  margin: 0;
}
.flex-container {
  display: flex;
  align-items: center;
}
.flex1,
.flex2,
.flex3 {
  display: flex;
  flex: 1 1 0;
  border: 1px solid black;
}
.flex2 {
  justify-content: space-around;
}
.flex3 {
  justify-content: flex-end;
}
.flex-item {
  width: 50px;
  height: 50px;
  background: orange;
}
.flex-item.plz-center {
  width: 25px;
}
.flex-item.big {
  width: 150px;
}
<div class="flex-container">
  <div class="flex1">
    <div class="flex-item"></div>
  </div>
  <div class="flex2">
    <div class="flex-item plz-center"></div>
  </div>
  <div class="flex3">
    <div class="flex-item big"></div>
  </div>
</div>
Dylan Stark
  • 2,325
  • 17
  • 24