Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Change the auto-placement behaviour of grid items with grid-auto-flow


    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?



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Now, on mock up, we have 10 grid items inside a container, and they're all numbered from 1 to 10. In our CSS, we have display grid on the container, taking up all the available height, a five pixel gutter, and we have explicit grid template columns and grid template rows.

    We have an empty row down here because we've specified that we want four grid template rows. As we can see, CSS grid is automatically placing our grid items in a row as in from left to right. That's the default behavior for CSS grid. If we look under the hood, we can see this being applied.

    We can change this value to column. Now, all the items are being placed from top to bottom. Now we have an empty column on the end, instead of an empty row on the bottom. We can also pass the dense keyword to grid auto flow to demonstrate what that does.

    Let's apply some grid columns to some of our grid items. We'll target the second and third grid items, and they're going to span across two columns. Let's use grid auto flow row. Now, our second grid item, and our third grid item are taking up two columns' width. Now, we have a gap over here, because there's not enough room for three.

    If we wanted to fill that gap with the nearest available cell that will fit in there, we can do so by saying row dense. Now our fourth item moves to fill the gap. We can also use this on column, so let's change grid auto flow back to column.

    We'll make our second and third grid items span across three columns, and we'll target our eighth grid item and have it span across three rows. Now, we can see an implicitly created track line created for us, because grid has nowhere else to put the 10th item.

    Of course, we could include it in our grid structure using column dense. Finally, when we reorder our grid items like this, what's actually happening to the DOM? Let's find out by going to our div tools. We can see that the order of them in the DOM hasn't changed at all from how we set them up in our mock up.