Layout
grid-auto-flow
grid-auto-flow sets whether grid items without a set position are placed along the rows or down the columns, and whether earlier empty cells get filled in.
Syntax
[ row | column ] || densePreview
Code
.box {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
grid-auto-flow: row dense;
}Controls
About
Values
row: the initial value. Items go from left to right along the first row, then on to the next row. New rows are added below when needed.column: items go from top to bottom down the first column, then on to the next column. New columns are added to the right when needed.dense: added afterroworcolumn(row dense), it fills earlier empty cells with later items.densealone is the same asrow dense.
Empty cells and dense
By default each item goes into the first free space after the previous item. An item that spans two columns and does not fit at the end of a row moves to the next row, leaving the cells behind it empty. With dense, the search starts from the beginning for every item, so later, smaller items fill the earlier gaps.
The preview on this page sets up a grid of three columns and three rows as helper declarations. Items 1 and 2 span two columns (grid-column: span 2), so with row the right cell of the first row stays empty, and with row dense item 3 moves into it.
dense makes the visual order differ from the HTML order, so keyboard navigation and screen readers no longer follow what people see. Use it for items whose order does not matter, such as a photo gallery.
Placing down the columns
With column, all items end up in one row unless grid-template-rows sets the number of rows. Added columns get their width from grid-auto-columns (initially auto).
Shorthand
In the grid shorthand it is written as the auto-flow keyword (grid: auto-flow dense / 1fr 1fr). Before the slash it means row, after the slash column.