4

This, this, and this question are similar but do not help.

The goal is for the children of a flexbox container to fill the space, but ensure each child shares the same width.

The problem is that rows with a different number of children cause their children to use different widths.

Box1 does not have this problem because there is only one row.

Box2 illustrates the problem because the children occupy two rows, and each row has a different number of children.

Codepen: https://codepen.io/anon/pen/BXZLPX

.box {
  display: flex;
  flex-grow: 1;
  flex-wrap: wrap;
  width: 1000px;
  background: blue;
  margin-bottom: 20px;
}

.child {
  flex: 1 1 0;
  min-width: 150px;
  max-width: 100%;
  height: 150px;
  border: 1px solid yellow;
}

#box2 {
  width: 700px;
  background: red;
}
<div id="box1" class="box">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>


<did id="box2" class="box">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>
Crashalot
  • 33,605
  • 61
  • 269
  • 439
  • 2
    css-grid maybe: https://jsfiddle.net/7d9htbzw/2/? – Temani Afif Jul 31 '19 at 20:35
  • 3
    This? https://stackoverflow.com/q/44154580/3597276 – Michael Benjamin Jul 31 '19 at 20:39
  • 1
    I closed this as a duplicate...and if I misunderstood, let me know and I'll reopen it. – Asons Jul 31 '19 at 21:31
  • @Michael_B Thanks for the link! Is there a way to do this while making the items square (e.g., height would need to be fluid along with width, and would need to match width). – Crashalot Jul 31 '19 at 21:39
  • You can use the `padding-top/bottom` trick (https://stackoverflow.com/questions/46548987/a-grid-layout-with-responsive-squares/46550527#46550527) to keep them square. Do note though, any content inside have to be absolute positioned, or else it will break. – Asons Jul 31 '19 at 21:44
  • @LGSon thanks! are you referring to this (which uses padding-bottom)? https://stackoverflow.com/a/19068538/144088 – Crashalot Jul 31 '19 at 21:47
  • Yepp, similar trick, though mine uses pseudo to overcome extra markup + avoid issue with flex child using padding with percent (should be fixed on newer browsers, still, some take their time to update) – Asons Jul 31 '19 at 21:49
  • @LGSon is there a SO you could share as reference? sounds like your approach is better. thanks again! :) – Crashalot Jul 31 '19 at 21:53
  • You want it ([a-grid-layout-with-responsive-squares](https://stackoverflow.com/questions/46548987/a-grid-layout-with-responsive-squares/46550527#46550527)) together with the dupe link at the top of your question? – Asons Jul 31 '19 at 21:55
  • @LGSon yes that's the use case, thanks so much for your help! – Crashalot Jul 31 '19 at 22:01

0 Answers0