Two steps are required when it comes to building grid designs:
Imagine we work with following code:
<div id="container">
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
</div>
The corresponding CodePen is of course available.
First, we need our container to display its content as a grid : #container { display: grid; }
. After that we need to slice down the container. There's two ways to do that:
#container {
display: grid;
grid-gap: 1em;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
}
Here we'll have a grid of 2 columns and 2 rows.
#container {
display: grid;
grid-gap: 1em;
grid-template-areas:
"div1 div2"
"div3 div4"
}
Same here but we use names. In both cases we set up a gap, which is the space between the child element of the container.
#div1 {
grid-column: 1;
grid-row: 1;
}
div1 will go in first column and first row.
#div1 {
grid-area: div1;
}
Here we declare the element's name. As div1 was the first name on the first line, #div1 element will go on first column and first row.
For the slicing part, we can use different units, exclusively or in a combination, such as:
We can also use functions, exclusively or in combination, such as:
For the filling part, we can set up precise coordinates which will be a line or a column line number with the syntax from / to
For instance, if our first div was supposed to fill the entire first line, we could write:
#div1 {
grid-column: 1 / 3;
grid-row: 1;
}
Where we are telling the brower to extend #div1 on column 1 and 2 (column 1 is between number 1 and 2 and column 2 between number 2 and 3).