Grid

Repeating rows and columns

If we have multiple columns and/or rows of identical dimensions, it makes sense to use the special repeat() function , which allows us to customize the rows and columns. For example, in the example above, the definition of identical rows and columns is repeated in the grid container:

1
2
grid-template-columns: 8em 8em 8em;
grid-template-rows: 5em 5em 5em 5em;

Here we see that the same dimensions are repeated—8em and 5em—for setting the column width and row height. Therefore, let’s rewrite the styles using the repeat function:

1
2
3
4
5
6
.grid-container {
    border: solid 2px #000;
    display: grid;
    grid-template-columns: repeat(3, 8em);
    grid-template-rows: repeat(4, 5em);
}

The first parameter of the repeat function represents the number of repetitions, and the second specifies the rows or columns. For example, the property grid-template-columns: repeat(3, 8em);specifies that three columns of 8em width should be defined.

Accordingly, the expression grid-template-rows: repeat(4, 5em)defines 4 lines of height 5em each.

You can specify repetition of multiple columns and rows:

1
2
3
4
5
6
.grid-container {
    border: solid 2px #000;
    display: grid;
    grid-template-columns: repeat(2, 7em 8em);
    grid-template-rows: 6em repeat(3, 5em);
}

In this case, 4 columns will be created: two columns with a width of 7em and 8em will be repeated twice.

In the case of rows, four rows will be created. The first will have a height of 6em, and the other three will have a height of 5em.

Grid property

The grid property combines the grid-template-rowsand properties grid-template-columnsat once and allows you to set settings for rows and columns in the following format:

1
grid: grid-template-rows / grid-template-columns;

For example, we have the following grid container class definition:

1
2
3
4
5
6
.grid-container {
    border: solid 2px #000;
    display: grid;
    grid-template-columns: 8em 8em 8em;
    grid-template-rows: 5em 5em 5em 5em;
}

We can shorten this class as follows:

1
2
3
4
5
.grid-container {
    border: solid 2px #000;
    display: grid;
    grid: 5em 5em 5em 5em / 8em 8em 8em;
}

Or, again using the function repeat(), you can further shorten the grid definition:

1
2
3
4
5
.grid-container {
    border: solid 2px #000;
    display: grid;
    grid: repeat(4, 5em) / repeat(3, 8em);