We can change the automatic behaviour of what order our grid items appear. We can even re-order the items in our grid to fill available space using the dense
keyword. How do we approach this using grid-auto-flow
?
By default 'grid-auto-flow' is 'row'.
For example, we have this setup:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>change-the-auto-placement-behaviour-of-grid-items-with-grid-auto-flow</title> <style> .container > * { background-color: antiquewhite; } .container { display: grid; height: 100vh; grid-gap: 10px; grid-template-columns: repeat(4, 1fr); grid-template-rows: repeat(4, 1fr); } </style> </head> <body> <div class="container"> <div class="grid-item">1</div> <div class="grid-item">2</div> <div class="grid-item">3</div> <div class="grid-item">4</div> <div class="grid-item">5</div> <div class="grid-item">6</div> <div class="grid-item">7</div> <div class="grid-item">8</div> <div class="grid-item">9</div> <div class="grid-item">10</div> </div> </body> </html>
It should looks like:
Notice how items flows:
1->2->3->4
5->6->7->8
9->10
Now if we change 'grid-auto-flow' to 'column':
As we can see, now the how items flows:
1 5 9
2 6 10
3 7
4 8
So after understand how item flows for 'grid-auto-flow', let's see how 'grid-auto-flow' can help us auto fill the hole.
For example we have this setup:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>change-the-auto-placement-behaviour-of-grid-items-with-grid-auto-flow</title> <style> .container > * { background-color: antiquewhite; } .container { display: grid; height: 100vh; grid-gap: 10px; grid-template-columns: repeat(4, 1fr); grid-template-rows: repeat(4, 1fr); grid-auto-flow: row; } .grid-item:nth-of-type(2) { grid-column: span 2; } .grid-item:nth-of-type(3) { grid-column: span 3; } .grid-item:nth-of-type(8) { grid-row: span 3; } </style> </head> <body> <div class="container"> <div class="grid-item">1</div> <div class="grid-item">2</div> <div class="grid-item">3</div> <div class="grid-item">4</div> <div class="grid-item">5</div> <div class="grid-item">6</div> <div class="grid-item">7</div> <div class="grid-item">8</div> <div class="grid-item">9</div> <div class="grid-item">10</div> </div> </body> </html>
It looks like:
As you can see, after item 2, there is a gap which item 3 cannot fit in. In this case, we can use 'dense' to help.
Code:
grid-auto-flow: row dense;
As you can see, item 4 fill the gap after item 2.
Now last, let see 'column dense' case:
If with out 'dense', it looks like:
As you can see, it supposes to have 4 cols , but no it has 5 cols, because item 10 have no space leave. So now if we add 'column dense':
grid-auto-flow: column dense;