Create a Grid

Here we create a basic 3x3 grid with a small gutter between the grid tracks.

We'll create a basic grid that looks like this:

A basic grid
A basic 3x3 grid (3 rows and 3 columns).

Here's the code:

Try it

Let's take a closer look at that code.

The HTML markup for the grid looks like this:

So this is just a normal snippet of HTML consisting of elements nested inside an outer element. But for our purposes, the outer div is the grid container. All elements nested within it are grid items.

But it's not a grid until we apply some CSS to it.

So here's the CSS code that creates the grid:

This rule applies to the outer div (because it's been assigned the #grid ID).

Here's an explanation of each declaration within that rule:

display: grid
Turns the element into a grid container. This is all that's required in order to create a grid. We now have a grid container and grid items. The grid value generates a block-level grid container box. You can also use display: inline-grid to create an inline-level grid container box, or display: subgrid to create a subgrid (this value is designed to be used on grid items themselves).
grid-template-rows: 1fr 1fr 1fr
Explicitly sets the rows of the grid. Each value represents the size of the row. In this case all values are 1fr (which means it takes up the available free space), but they could just as easily have been done using a different unit, such as 100px, 7em, 30%, etc. You can also provide line names along with the track sizes (i.e. row and column sizes). See grid-template-rows for more information.
grid-template-columns: 1fr 1fr 1fr
Same as above except it defines the columns of the grid. See grid-template-columns for more information.
grid-gap: 2vw

Sets the gutter. The gutter is the gap in between the grid items. Here, we use the vw length unit (this is relative to the viewport's width), but we could just as easily have used 10px, 1em, etc.

The grid-gap property is actually a shorthand property for the grid-row-gap and grid-column-gap properties. See grid-gap for more information.

The other part of the code simply applies various styles to the grid items:

The repeat() Function

You can use the repeat() function to repeat a track definition for a specified number of times.

For example, instead of doing this:

You can do this:

This can reduce the amount of code you need to write, especially if you're working with a large and repetitive grid.