8

What I want as a result:

I have three elements in a container that is a display: flex I want the left item to be aligned to the left, and the right item to the right. With the center item aligned in the center.

space-between is not the fix. It is not the solution I am looking for. This is because the elements are differing widths. Even with differing widths, I still want the middle element to be centered.

This could be fixed with a wrapper. and then put a flex: 1 on the wrappers, then within those wrappers, have the elements themselves. Again, this is not the fix I am looking for. I cannot use wrappers in my situation.

.parentContainer {
  display: flex;
  justify-content: center;
  align-items: center;
}

.parentContainer > *{
   background: red;
   text-align: center;
}
<div class="parentContainer">
 <div class="left">small</div>
 <div class="middle">medium element here</div>
 <div class="right">longer element is here too</div>
</div>
TylerH
  • 20,799
  • 66
  • 75
  • 101
user10741122
  • 781
  • 1
  • 12
  • 26
  • Apols, I had a slight error in my first go-around. `flex:1` justified the inner divs correctly, but *within those divs* we still needed to align the text. – cssyphus Jan 23 '19 at 21:31

2 Answers2

6

The primary way to achieve this layout – because it's clean and valid – is with flex: 1 on the items. That method is explained in the following post, but is also ruled out in this question.

An alternative method involves CSS absolute positioning:

.parentContainer {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.middle {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

/* non-essential decorative styles */
.parentContainer > * { background: orange; text-align: center; padding: 5px; }
p { text-align: center;}
p > span { background-color: aqua; padding: 5px; }
P > span:first-child { font-size: 1.5em; }
<div class="parentContainer">
  <div class="left">small</div>
  <div class="middle">medium element here</div>
  <div class="right">longer element is here too</div>
</div>
<p>
  <span>&uarr;</span><br>
  <span>true center</span>
</p>

This method is explained in the following posts:

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

I think you can use a different approach. This is my suggestion.

.parentContainer {
  display: table;
  width: 100%;
  background: lightblue;
  border-collapse: collapse;
}

.parentContainer > div {
   display: table-cell;
   width: 33%;
}

.parentContainer > div:nth-child(1) {
  text-align: left;
}

.parentContainer > div:nth-child(2) {
  text-align: center;
}

.parentContainer > div:nth-child(3) {
  text-align: right;
}
<div class="parentContainer">
 <div>small</div>
 <div>medium element here</div>
 <div>longer element is here too</div>
</div>
Pablo Darde
  • 5,844
  • 10
  • 37
  • 55