The repeat function in CSS grids
If you have several columns that are set to the same size, you can simplify the notation by using the repeat
function. The first parameter of this function specifies the number of columns, and the second parameter specifies their width. Let's look at examples of how this works.
Example
Let's say we have three columns of the same size:
#parent {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
Let's simplify the recording using repeat
:
#parent {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
Example
Let's say we have three columns of the same size, and the fourth one of a different size:
#parent {
display: grid;
grid-template-columns: 1fr 1fr 1fr 2fr;
}
Let's simplify the recording using repeat
:
#parent {
display: grid;
grid-template-columns: repeat(3, 1fr) 2fr;
}
Example
Let's say we have the first three columns of one size, and the second three columns of a different size:
#parent {
display: grid;
grid-template-columns: 1fr 1fr 1fr 2fr 2fr 2fr;
}
Let's simplify the recording using repeat
:
#parent {
display: grid;
grid-template-columns: repeat(3, 1fr) repeat(3, 2fr);
}
Example
Let's say we have the first three columns of one size, then another column, and then three more columns of a different size:
#parent {
display: grid;
grid-template-columns: 1fr 1fr 1fr 3fr 2fr 2fr 2fr;
}
Let's simplify the recording using repeat
:
#parent {
display: grid;
grid-template-columns: repeat(3, 1fr) 3fr repeat(3, 2fr);
}
Example
The simplification works for any unit of size. Let's say for example we have three columns in pixels:
#parent {
display: grid;
grid-template-columns: 200px 200px 200px;
}
Let's simplify the recording using repeat
:
#parent {
display: grid;
grid-template-columns: repeat(3, 200px);
}
Practical tasks
Make 4
columns the same size using repeat
.
Make 4
columns of 100px
size, and another 3
columns of 2fr
size.
Make 2
columns of 100px
, another 3
columns of 200px
, then a column of 1fr
, and then 2
columns of 10%
.