CSS Grid: Setting columns and rows dimensions

Many times you might have a fixed header size, a fixed footer size, and the main content that is flexible in height, depending on its length. In this case you can use the auto keyword:

.container {
  display: grid;
  grid-template-rows: 100px auto 100px;
}

In this example we made pretty, regular grids by using the same values for rows and the same values for columns:

.container {
  display: grid;
  grid-template-columns: 200px 200px;
  grid-template-rows: 100px 100px;
}

A grid with 2 columns and 2 rows

You can specify different values for each row/column, to create a lot of different designs:

.container {
  display: grid;
  grid-template-columns: 100px 200px;
  grid-template-rows: 100px 50px;
}

A grid with varying columns and rows dimensions

Another example:

.container {
  display: grid;
  grid-template-columns: 10px 100px;
  grid-template-rows: 100px 10px;
}

A grid with varying columns and rows dimensions

Using fractions, percentages and rem

Specifying the exact width of each column or row is not ideal in every case.

A fraction is a unit of space.

The following example divides a grid into 3 columns with the same width, 1/3 of the available space each.

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

You can also use percentages, and mix and match fractions, pixels, rem and percentages:

.container {
  grid-template-columns: 3rem 15% 1fr 2fr
}

Using repeat()

repeat() is a special function that takes a number that indicates the number of times a row/column will be repeated, and the length of each one.

If every column has the same width you can specify the layout using this syntax:

.container {
  grid-template-columns: repeat(4, 100px);
}

This creates 4 columns with the same width.

Or using fractions:

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

Lessons in this unit:

0: Introduction
1: grid-template-columns and grid-template-rows
2: ▶︎ Setting columns and rows dimensions
3: Gap between the cells
4: Span items on multiple columns and/or rows
5: Minimum row width
6: Layout using grid-template-areas
7: DEMO Example: simple grid layout
8: DEMO Example: grid layout with header, sidebar, content and footer