grid overview

February 19, 2024 - Reading time: 4 minutes

Two steps are required when it comes to building grid designs:

  1. slice a container into... a grid
  2. fill the cells or area of cells with elements

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.

Slicing

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:

Classic way

#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.

By name

#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.

Filling

Classic way

#div1 {
grid-column: 1;
grid-row: 1;

}

div1 will go in first column and first row.

By name

#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.

Units and functions

For the slicing part, we can use different units, exclusively or in a combination, such as:

  • fraction (fr) - the browser divides the screen with the all fractions that were specified
  • relative units: %, vw, vh, auto...
  • fixed units: px
  • keywords: min or max-content, auto

We can also use functions, exclusively or in combination, such as:

  • repeat(nbOfTimes, unit)
  • minmax(minSize, maxSize)

Coordinates

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).