stackjlei
stackjlei

Reputation: 10035

Display flex even space between children regardless of children width

I have two instances of the same row-component that has display: flex and justify-content: space-between:

<div class="component-row">
  <div>looooooooooong</div>
  <div>short</div>
  <div>mediummm</div>
</div>

<div class="component-row">
  <div>looooooooooong</div>
  <div>short</div>
  <div>mediummm</div>
</div>

The spacing between the children of each component will be different because the children have different widths. Without changing the order of the children, how can I make sure that both component instances have the same amount of space between each of their children? Within the instance, the space (ex. the space between long and short) doesn't have to be equal - what I want is the space between the 1st and 2nd child of both instances to be the same, and the space between the 2nd and 3rd child of both instances to be the same.

Upvotes: 1

Views: 1482

Answers (2)

Asons
Asons

Reputation: 87191

The most obvious would be to give each item a width, though if you can't or don't want, flexbox is not the best solution, a grid is.

As CSS Grid lacks good browser support, CSS Table doesn't, and is the perfect choice to accomplish this task.

.component-container {
  display: table;
  width: calc(100% - 40px);
}
.component-row {
  display: table-row;
}
.component-row div {
  position: relative;
  display: table-cell;
  border: 1px solid gray;
}
.component-row div:nth-child(2) {
  left: 20px;
}
.component-row div:nth-child(3) {
  left: 40px;
}
<div class="component-container">
  <div class="component-row">
    <div>looooooooooong</div>
    <div>mediummm</div>
    <div>short</div>
  </div>

  <div class="component-row">
    <div>short</div>
    <div>looooooooooong</div>
    <div>mediummm</div>
  </div>
</div>

Upvotes: 1

Troyer
Troyer

Reputation: 7013

It sounds really easy solution but it is, just give a fixed width on a class and then place it on the .component-row childrens.

.component-row {
  display: flex;
  justify-content: space-between;
}

.eq1 {
  width: 30%;
}
.eq2 {
  width: 20%;
}
.eq3 {
  width: 35%;
}
<div class="component-row">
  <div class="eq1" style="background-color: red;">looooooooooong</div>
  <div class="eq2" style="background-color: purple;">short</div>
  <div class="eq3" style="background-color: pink;">awdasdsdasad</div>
</div>

<div class="component-row">
  <div class="eq1" style="background-color: green;">looooooooooong</div>
  <div class="eq2" style="background-color: yellow;">srt</div>
  <div class="eq3" style="background-color: blue;">mediummm</div>
</div>

Upvotes: 2

Related Questions