The CSS Grid Layout Module offers a grid-based layout system, with rows and columns. It is powerful tool that allows for two-dimensional and flexible layouts to be created on the web. And for those who prefer to build designs from scratch, it works a lot better that other CSS frameworks like Bootstrap, Foundation, or Semantic UI.
Let’s directly jump into the practical implementation.
Grids will only work if you have particular HTML layout - Parent & Child. Parent is the actual grid and child are the actual content inside the grid.
<div class="wrapper">
<div class="item-1">one</div>
<div class="item-2">two</div>
<div class="item-3">three</div>
<div class="item-4">four</div>
<div class="item-5">five</div>
<div class="item-6">six</div></div>
To make wrapper div into grid, simply give it a display: grid;
.wrapper { display: grid;}
To create columns and rows of the grid, we have to use the grid-template-row and grid-template-column properties.
.wrapper {
display: grid; grid-template-columns: 100px 100px 100px;
grid-template-rows: 50px 50px;}
As you can see, we have specified the three values to grid-template-columns & two values to grid-template-rows . It means the layout will be of three columns & two rows.
This is how the layout will look:
Before placing items in Grids, it is important to understand the ‘grid lines’.
To position and resize the items we’ll target them and use the grid-column and grid-row properties:
.item-1 {
grid-column-start: 1;
grid-column-end: 4;}
OR
.item-1 { grid-column: 1/4; //Shorthand property}
This is how .item-1 will look like:
On the other hand, if we change to this
.item-1 {
grid-row-start: 1;
grid-row-end: 4;}
OR
.item-1 { grid-row: 1/4; //Shorthand property}
This is how the .item-1 will look like:
As you can see, grid-rows & grid-column allows you to make complex layouts without any change in HTML DOM.
The grid-area property can be used as a shorthand property for the grid-row-start/ grid-column-start/ grid-row-end and the grid-column-end properties.
.item5 { grid-area: 1 / 2 / 3 / 4;}
This is how it will look:
We can assign a particular name to grid items using grid-area property.
HTML:
<div class="wrapper">
<div class="item-1">Header</div>
<div class="item-2">Left Sidebar</div>
<div class="item-3">Main</div>
<div class="item-4">Right sidebar</div>
<div class="item-5">Footer</div></div>
CSS:
.container { display: grid; grid-template-areas:
'header header header header header header'
'menu main main main main right'
'menu footer footer footer footer footer';}
.item-1 { grid-area: header; }
.item-2 { grid-area: menu; }
.item-3 { grid-area: main; }
.item-4 { grid-area: right; }
.item-5 { grid-area: footer; }
That was a quick basic guide to CSS Grids. Here are the best resources to dive in further: