Learn CSS Grid with Pinegrow

Dynamic columns with repeat and auto-fit

We’ll improve the image gallery by making the number and size of the columns adjust to the available space.


The first problem with our Gallery is that we fixed the number of columns to 3. It would be better that the number of columns would adjust to the size of the content area.

Again, CSS Grid has tools that let us do that.

The first one is called Repeat.

In situations where we have a bunch of same columns or rows we can just use one Repeat declaration instead of defining all those columns.

So, let’s get rid of two columns.

Double click on the Size of the first column.

Among other presets, we have the Repeat declaration.

Let’s use it.

Repeat has two parameters: the first one is the number of columns or rows that we want to create and the second is their size.

So this statement will create 3 columns of 200px each.

Let’s change 200px to 1fr and we are where we started – with 3 columns that divide all available space.

What we need is that the number of columns adjusts to the space that is available for them.

We get that by replacing the number of columns – 3 in our case – with the keyword auto-fit. That tells the browser to fit as many columns as possible into the available space.

But at the moment, we’re using 1fr as the columns size and all we get is one huge column per row.

We need to tell the browser to be more flexible when it comes to sizing the columns.

And we do that with the help of minmax keyword.

Instead of just saying 1fr we say minmax(100px, 1fr).

So, there should be as many columns as possible in a row, keeping their size at at least 100px. The 1fr means that in case there is some empty space in the row, the space should be equally divided among the columns.

We can see this in action here…

Columns are getting larger, until we reach a point where an additional 100px column can be added to the row.

This behavior is perfect for our gallery.

But we still have a problem with rows that are automatically added to the grid. We’ll fix that next.