I've got four div's in a flexbox grid. I want them to wrap two at a time, like this:
+-----------------------+
| 1 | 2 | 3 | 4 |
+-----------------------+
+-----------+
| 1 | 2 |
+-----------+ THIS IS WHAT I WANT
| 3 | 4 |
+-----------+
+-----+
| 1 |
+-----+
| 2 |
+-----+
| 3 |
+-----+
| 4 |
+-----+
Now, this seems easy enough, just nest them inside new flex containers and apply flex-wrap, and give the cells some min-widths. However, this has the side-effect of making the middle view look like this:
+-----------+
| 1 | 3 |
+-----------+ NOT WHAT I WANT
| 2 | 4 |
+-----------+
Apparently, flexbox wants to first wrap the inner div's instead of considering them rows. In order to keep all of the other wrapping working, setting flex-basis (to e.g. 100%) for the nested div's is not an option. In order to keep everything dynamic (for instance adding a third cell to one of the rows), setting %-widths on the cells is not an option. And in order to avoid hard breakpoints and base wrapping on (dynamic) content width, I'd really like to avoid media queries.
Can this be achieved with flexbox and without media queries?
JSFiddle
div {
box-sizing: border-box;
margin: 2px;
}
.grid {
display: flex;
flex-flow: row wrap;
border: 2px solid blue;
flex: 1;
}
.cell {
flex: 1;
min-width: 100px;
border: 2px solid red;
background: white;
height: 100px;
}
<div class="grid">
<div class="grid">
<div class="cell">1</div>
<div class="cell">2</div>
</div>
<div class="grid">
<div class="cell">3</div>
<div class="cell">4</div>
</div>
</div>
EDIT: I know I can make the inner .grid
not wrap at all, but what I really want is for all the cells to wrap below each other if space is super tight. (As in the first illustration.)
With flexbox and grid you can make responsive layouts without having to define fixed breakpoints with media queries.
Responsive Pixel — An Alternative to Media Query for Responsive Resizing.
Media queries should probably be on all sites. Flexbox is a layout tool, basically. You have that, CSS tables, float, grid, etc. You lay out your page depending on what's best (e.g. flexbox) and media queries to help it flow naturally as you resize the page smaller.
You need to tell the children-elements of .grid .grid
to flow in a row:
div {
box-sizing: border-box;
margin: 2px;
}
.grid {
display: flex;
flex-flow: row wrap;
border: 2px solid blue;
flex: 1;
}
.grid .grid {
flex-flow: row; /* this is your fix */
}
.cell {
flex: 1;
min-width: 100px;
border: 2px solid red;
background: white;
height: 100px;
}
<div class="grid">
<div class="grid">
<div class="cell">1</div>
<div class="cell">2</div>
</div>
<div class="grid">
<div class="cell">3</div>
<div class="cell">4</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With