Intro to CSS Grid Layout Part 1

This post is an intro to CSS grid layout part 1. You can use CSS Grid to easily build a two-dimensional grid-based layout. This is the first part of the article which will specifically focus on the basic properties.


CSS Grid Layout Example

The above image represents basics of CSS grid layout. It has two rows and three columns. Each brown box is called a grid item. There is a gap between the items which is called a gutter.


Grid Container

It is the container of the grid. You can declare the container by calling this in the CSS file.

.container {
    display: grid;
}


Row/Column

Row and column of the container can be specified by calling the following after display: grid

.container {
  grid-template-rows: 150px 150px;
  grid-template-columns: 150px 150px 150px;    
}

The above declares two rows and three columns. Each row/column has width of 150px. However, it is a bit inconvenient to specify all the rows and columns separately. For that you can use the keyword repeat.

.container {
  grid-template-rows: repeat(2, 150px);
  grid-template-columns: repeat(3, 150px);
}

The above code is exactly same as the first one. If you want to have different width for certain row or column, you can just specify it like this.

.container {
  grid-template-rows: repeat(2, 150px);
  grid-template-columns: repeat(2, 150px) 200px;
}

Now you have 2 rows with the same width but 3 columns of which first 2 columns have 150px and the last column has 200px.

Note the numbers around the row and column (row: 1,2,3 and column:1,2,3,4) are row lines and column lines.


Gap (gutter)

The space between each grid item. You can define the row/column gap separately or the same depending on the property.

.container {
  grid-row-gap: 30px;
  grid-column-gap: 50px;
}

The above code has 30px for row gap and 50px for column gap. Row gap is the space between two rows (there are only two rows).
Column gap is the spaces between three columns (there are only three columns)

If you would like to have the same space for all the gaps, you can use this property.

.container {
  grid-gap: 30px;
}


Conclusion

We have taken a look at very basics of CSS grid layout – declaring two-dimensional grid with rows and columns. In next post, I will go over more of CSS grid. fractional units, positioning of grid items

Leave a Reply

Your email address will not be published.