iantresman iantresman - 8 days ago 5
CSS Question

Make flex items wrap to existing lines, not new lines

I'm trying to style a table (I can't change the HTML) as a flexbox that flows responsively without leaving gaps.

My starting table on wide screens

+---+---+---+---+
| A | B | C | D |
+---+---+---+---+
| w | x | y | z |
+---+---+---+---+


When I narrow the screen this is what I get:

+---+---+---+
| A | B | C |
+---+---+---+
| D |
+---+---+---+
| w | x | y |
+---+---+---+
| z |
+---+


What I'd like:

+---+---+---+
| A | B | C |
+---+---+---+
| D | w | x |
+---+---+---+
| y | z | |
+---+---+---+


Here is the CSS I have so far:



/* Relevant flexbox stuff */
.respondable {
display: flex;
}
.respondable tr {
display: flex;
flex-direction: row;
flex-wrap: wrap
}

/* Pretty stuff */
.respondable {
border-collapse: collapse;
}
.respondable td {
border: 1px solid black;
border-collapse: collapse;
width: 100px;
text-align: center;
background: #eeeeee
}

Narrow screen to see D jump onto line of its own
<table class="respondable">
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>w</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
</table>





https://jsfiddle.net/h9s7nkar/

Answer

When flex items wrap they create new lines.

In other words, a flex item won't wrap to an existing line.

That's why the second row of items gets pushed to a third row when the top row starts wrapping.

From the spec:

6. Flex Lines

A multi-line flex container (i.e. one with flex-wrap: wrap or flex-wrap: wrap-reverse) breaks its flex items across multiple lines, similar to how text is broken onto a new line when it gets too wide to fit on the existing line.

The quickest and easiest solution would be to put all flex items in the same container. (I understand you can't alter the HTML.)