Your First Grid
Create a grid
The first thing we want to do is create a grid container. We can do this by declaring display: grid
on the container element. In this example we are using a div with the class of container
.
Define rows and columns
There are several ways to define rows and columns. For our first grid, we will use properties grid-template-columns
and grid-template-rows
. These properties allow us to define the size of the rows and columns for our grid. To create two fixed-height rows of 150px and three fixed-width columns of 150px, simply write:
grid-template-columns: 150px 150px 150px;
grid-template-rows: 150px 150px;
To add a fourth column that is 70px wide, write:
grid-template-columns: 150px 150px 150px 70px;
...and so on to add more columns.
Add a gutter
Adding a gutter to your grid is amazingly easy with CSS Grid Layout. Simply add:
grid-gap: 1rem;
That simple line gives you an equal-sized gutter between all rows and columns. To define the gutter size for columns and rows individually, you can use the grid-column-gap
and grid-row-gap
properties instead.
Now let's put that all together. Here is our HTML:
<div class="container">
<div class="item item1"></div>
<div class="item item2"></div>
<div class="item item3"></div>
<div class="item item4"></div>
<div class="item item5"></div>
<div class="item item6"></div>
</div>
With just a few lines of CSS, we can create a simple grid:
.container {
display: grid;
grid-template-columns: 150px 150px 150px;
grid-template-rows: 150px 150px;
grid-gap: 1rem;
}
Here is the result: