Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

How and why to use the repeat function in CSS Grid

Let's say we have a layout made of 10 equal-width columns. Then the container element will look like this:

.container {
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;

It's a bit troublesome to write a line where you paste ten times the same 1fr. Imagine how fun it's to read this line. Luckily we have the repeat function for situations like this one.

.container {
    grid-template-columns: repeat(10, 1fr);

A big readability improvement. You tell the function how many times to repeat, and what to repeat.

If works for both the grid-template-columns and grid-template-rows.

We can give it also a pattern to repeat:

.container {
    grid-template-columns: repeat(3, 1fr 50px);
    // it will create 6 columns
    // 1fr 50px 1fr 50px 1fr 50px 

Using the CSS grid repeat function with named lines

And we can even use it with named lines.

.container {
    grid-template-columns: repeat(3, [col-start ] 1fr [col-end] );
    // it will create 3 columns
    // [cstart ] 1fr  [cend] [cstart ] 1fr  [cend]  [cstart ] 1fr  [cend] 

Given the fact that we will have the same name for the columns, we will need to a second parameter in the grid-column to indicate instance number of the name we want to place an element:

.my-element {
    grid-column: cstart 2 / cend 2;

Using the repeat function with auto-fill

But what if we want to have a layout where we want to have as many columns of 200px as they fit in the width of the container? Well, for this we can use the auto-fill:

.container {
    grid-template-columns: repeat( auto-fill , 200px );
    // it will  make as many 200px columns as possible 
    // eq: your screen is 1500px , it will make 7 columns

And that's all for now, folks! Have a fantastic day!

Home Screencasts Best of Newsletter Search X