DEV Community

Cover image for Creating Your First CSS Grid Layout.
Prince Unachukwu
Prince Unachukwu

Posted on • Edited on

Creating Your First CSS Grid Layout.

CSS grid layout or CSS grid is a technique in Cascading Style Sheets that allows web developers to create complex responsive web design layouts more easily and consistently across browsers. There have been other methods for controlling web page layout methods, such as tables, CSS floats, and CSS flex box. CSS grid has an advantage over the popular CSS flex box, is that it allows web developers create responsive layouts in 2-dimensional space when the need arises
Enough talk, Let's get right into it!

YOUR FIRST GRID

Create a grid
The first step is to 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. The following code is used to create two fixed-height rows of 150px and three fixed-width columns of 150px.

grid-template-columns: 150px 150px 150px;
grid-template-rows: 150px 150px;
Enter fullscreen mode Exit fullscreen mode

Add a gutter (The space between rows and columns in a grid.)

grid-gap: 1rem;
Enter fullscreen mode Exit fullscreen mode

That simple line above 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>
Enter fullscreen mode Exit fullscreen mode

Here is the CSS

.container {
  display: grid;
  grid-template-columns: 150px 150px 150px;
  grid-template-rows: 150px 150px;
  grid-gap: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

An additional CSS can be added to give each div item a background and border so we can get so see the grid on our screen

   .item{
      border: solid 3px black;
      background: rgba(6, 22, 169, 0.792);
    }
Enter fullscreen mode Exit fullscreen mode

And Voila!, You've created your first Grid Layout

Alt Text

Top comments (0)