Grid Layout 211
Declaring and Defining the Grid
The first step in creating a grid is to declare the grid container, the element
used as the grid’s foundation. The dimensions of the grid container are
the limits of the grid, and all of the grid’s properties are applied to it. To
declare the grid container, use the display property with the new value grid
like this:
E { display: grid; }
This declaration creates a block-level grid container. The next step is
to define its tracks (rows and columns). You can define tracks on an explicit
grid, with a precise number of columns and rows, or on an implicit grid, which
is created relative to its content. You can also combine both explicit and
implicit grids, and I’ll explain each in turn.
Creating Explicit Grids by Setting Track Size
In an explicit grid, you can define a specific number of grid tracks by
setting their size using a pair of properties: grid-template-columns and
grid-template-rows. The value for each property is a space-separated list of
lengths, which sets the width of the column or the height of the row. For
example, the following code snippet creates a three-column grid, where
the first and last columns are set to 20 percent of the width of the grid con-
tainer and the second to 60 percent of the width:
E { grid-template-columns: 20% 60% 20%; }
You can use percentages or any unit of length, including the specialized
grid unit of length called a fraction (fr). One fr is equivalent to one equal
share of any unassigned length in a grid. I’ll explain what I mean. Take a
look at this code, where the grid container has a width value of 600px, and
three columns each have a defined width:
E {
display: grid;
grid-template-columns: 100px 100px 200px;
width: 600px;
}
The total width of the columns is 400px, which is 200px less than the
width of the container. In this case, adding an extra column of 1fr width
makes that column as wide as all of the remaining space, or 200px:
E { grid-template-columns: 100px 100px 200px 1fr; }
Adding another column of the same width makes both columns 100px
in width:
E { grid-template-columns: 100px 100px 200px 1fr 1fr; }