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:
Here's the code:
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
Here's an explanation of each declaration within that rule:
- 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
gridvalue generates a block-level grid container box. You can also use
display: inline-gridto create an inline-level grid container box, or
display: subgridto 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
30%, etc. You can also provide line names along with the track sizes (i.e. row and column sizes). See
grid-template-rowsfor more information.
grid-template-columns: 1fr 1fr 1fr
- Same as above except it defines the columns of the grid. See
grid-template-columnsfor more information.
Sets the gutter. The gutter is the gap in between the grid items. Here, we use the
vwlength unit (this is relative to the viewport's width), but we could just as easily have used
The other part of the code simply applies various styles to the grid items:
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.