How does the `dense` keyword affect the way items are implicitly added to the grid?


#1

Question

How does the dense keyword affect the way items are implicitly added to the grid?

Answer

By default, items are placed sequentially within our grid, even if this creates “holes” or gaps in the grid. For example, say we have a 200px space at the end of a row but a 300px grid item. As this grid item is too large for the space, a new row will be created for the item. By default, the auto-placement algorithm will never backtrack to fill holes like this and the 200px gap will never be filled even if there exists smaller items that might fit there.

Applying the grid-auto-flow: dense; declaration changes this default behavior such that all grid items will be packed into the grid as tightly as possible. The algorithm will backtrack to see if a grid item might fit within a previously created hole. Note, this means that grid items might be placed out of order.