Flexbox vs. Grid: controlling the direction of the flow
Setting a parent to display: flex lays its children out left-to-right by default. The flex-direction property (or the flex-flow shorthand) changes that, stacking children vertically in a column instead.
CSS Grid can achieve a similar arrangement. The target here is a layout where children are aligned as follows:
1 3 5 7
--------
2 4 6 8
...rather than the default:
1 2 3 4
--------
5 6 7 8
How Grid fills space by default
A grid container positions its children left-to-right, just like flexbox. Given a grid with 6 columns and 2 rows, the children fill every column of the first row before starting the second — standard line-wrapping behavior.
.parent {
display: grid;
grid-template-columns: repeat(6, 1fr);
grid-template-rows: repeat(2, 150px);
gap: 20px;
}
The desired behavior is the opposite: children should fill column 1, row 1 and row 2 before moving on to the next column, i.e. column wrapping. Placing each item individually on the grid produces the layout, but it means setting the position of every child by hand.
.parent {
display: grid;
grid-template-columns: repeat(6, 1fr);
grid-template-rows: repeat(6, 150px);
}
.child-1 {
grid-column: 1;
grid-row: 1;
}
.child-2 {
grid-column: 1;
grid-row: 2;
}
.child-3 {
grid-column: 2;
grid-row: 1;
}
/* etc, etc. */
grid-auto-flow is the answer
The property that handles this automatically is grid-auto-flow, which tells a grid container how to fill unoccupied space with child elements. The required rule is:
.parent {
display: grid;
grid-auto-flow: column;
/* set up columns and rows here */
}
Its default value is row: children fill up each column until a row is complete, then flow into the row beneath — filling rows of the grid first. Setting it to column makes each new element fill all the space in column 1 before moving on to column 2, and so on.
.parent {
display: grid;
grid-auto-flow: column;
grid-template-columns: repeat(6, 1fr);
grid-template-rows: repeat(2, 150px);
}
That flow is the operative part of the name. Despite its off-putting appearance, the property is a useful one, and it makes the most sense when read as the CSS Grid equivalent of flex-direction.



