I'm trying to arrange "items" (child divs) in "containers" (parent divs) in a way that
- items wrap within flexible-width containers, so that containers are as narrow as possible, but in max. two rows
- containers wrap within the page (or within some wrapper/containercontainer).
This is what I want:
┌───┐┌─────────┐┌─────┐
│ █ ││ █ █ █ █ ││ █ █ │
│ █ ││ █ █ █ ││ █ █ │
└───┘└─────────┘└─────┘
Kind of the opposite of this, where the number of items per row is fixed, but the number of rows is flexible.
My attempt was to make containers and their parent display:flex
, to give the containers a fixed height that allows only two rows, and to give the containers a high flex-shrink
value, so they would try to be as narrow as possible and make their child items wrap.
But items don't wrap this way, instead, I get this
.wrapper {
display:flex;
flex-wrap:wrap;
font-size:2vw;
width:96vw;
}
.container {
flex:0 20 auto;
display:flex;
flex-wrap:wrap;
height:20vw;
margin:1vw;
background:skyblue;
}
.item {
position:relative;
width:10vw;
height:7vw;
margin:1vw;
background:orange;
}
<div class="wrapper">
<div class="container">
<div class="item">1a</div>
<div class="item">1b</div>
</div>
<div class="container">
<div class="item">2a</div>
<div class="item">2b</div>
<div class="item">2c</div>
<div class="item">2d</div>
<div class="item">2e</div>
<div class="item">2f</div>
<div class="item">2g</div>
</div>
<div class="container">
<div class="item">3a</div>
<div class="item">3b</div>
<div class="item">3c</div>
<div class="item">3d</div>
</div>
</div>
┌─────┐
│ █ █ │
│ │
└─────┘
┌───────────────┐
│ █ █ █ █ █ █ █ │
│ │
└───────────────┘
┌─────────┐
│ █ █ █ █ │
│ │
└─────────┘
Items don't feel any urge to wrap, instead they stretch the containers so that they get too wide to wrap, mostly occupy a full row.
Yes, I could brute-force two rows with the help of the backend, but that doesn't feel right :o[.
(Conditions: Height and width of items are defined. Number of items per container is variable, but limited so that each container will fit on the page.)
Any good ideas? Much appreciated! Thanks.