Once you have a grid container, the first thing you do is define how many columns and rows
you want. The grid-template-columns and grid-template-rows
properties are where the magic happens.
Grid Template Columns
You define columns by listing their sizes:
.container {
display: grid;
grid-template-columns: 200px 300px 200px;
/* three columns: 200px, 300px, 200px */
}
Each value is a track size. You can use any unit you like โ pixels, percentages, ems,
or the special fr unit.
The fr Unit
fr stands for "fraction." It distributes available space proportionally,
like flex-grow for grid tracks.
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
/* middle column gets twice the space of the sides */
}
This creates a three-column layout where the middle column is twice as wide as the side columns. No math required โ the browser figures it out.
Grid Template Rows
Same idea, but for rows:
.container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 100px 200px;
}
This creates two columns and two rows. Items fill the grid left to right, top to bottom, unless you place them manually.
The repeat() Function
Typing the same value over and over gets old fast. repeat() saves you:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
/* three equal columns โ same as 1fr 1fr 1fr */
}
repeat(4, 100px) gives you four columns of 100px each. You can even combine
repeat with fixed values: 200px repeat(2, 1fr).
The Gap Property
Like flexbox, grid has a gap property for spacing between tracks:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
This puts 20px between every column and row. You can also use row-gap and
column-gap separately if you need different spacing.