Introduction to CSS Grid

Tutorial 2 of 5

Introduction

Goal

This tutorial aims to introduce you to the world of CSS Grid, a powerful layout system in CSS. It provides a simple, efficient method to design your web layout in both rows and columns, perfect for complex web layouts.

Learning Outcomes

By the end of this tutorial, you will be able to understand how the CSS Grid works and be capable of using it to design your own web layouts.

Prerequisites

To get the most out of this tutorial, you should have a basic understanding of HTML and CSS.

Step-by-Step Guide

CSS Grid Layout is a 2-dimensional system, meaning it can handle both columns and rows. We define a grid container with display: grid and then we place child elements into the grid.

For a basic grid layout, you need to follow these steps:

  1. Set up a container and make its display style grid: display: grid.
  2. Specify the number of rows and columns and their sizes with grid-template-rows and grid-template-columns.
  3. Place the items into the grid with grid-column and grid-row.

Code Examples

Let's create a simple 3x3 grid:

.container {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  grid-template-rows: 100px 100px 100px;
}
.item {
  grid-column: 1 / 3;
  grid-row: 1 / 3;
}

In this example, .container is the grid container, and .item is a grid item. The grid-template-columns and grid-template-rows properties define the number and sizes of the rows and columns. The grid-column and grid-row properties on the item specify where the item should be placed in the grid.

Summary

In this tutorial, we have covered the basics of CSS Grid. You have learned how to create a grid container with display:grid and how to define and place grid items using grid-template-columns, grid-template-rows, grid-column, and grid-row.

For further learning, you can explore more about grid properties such as grid-gap, grid-auto-rows, grid-auto-columns, and grid-template-areas.

Practice Exercises

Now let's apply what we've learned with some exercises:

  1. Easy: Create a 2x2 grid with each cell of 50px by 50px.
  2. Medium: Place an item to span the first row.
  3. Hard: Create a grid with an area template. Name the areas and place items in them.

Solutions

  1. Easy:
.container {
  display: grid;
  grid-template-columns: 50px 50px;
  grid-template-rows: 50px 50px;
}
  1. Medium:
.item {
  grid-row: 1 / span 1;
  grid-column: 1 / span 2;
}
  1. Hard:
.container {
  display: grid;
  grid-template-areas: 
    "header header"
    "sidebar content"
    "footer footer";
}
.header {
  grid-area: header;
}
.sidebar {
  grid-area: sidebar;
}
.content {
  grid-area: content;
}
.footer {
  grid-area: footer;
}

Keep practicing and exploring more about CSS Grid. Happy coding!