1. Introduction
This tutorial aims to help you understand and make use of CSS Grid, a powerful tool that enables the creation of intricate layouts with ease. By the end of this guide, you'll be able to construct rows and columns and control their size and positions accurately.
You'll learn:
Prerequisites: Basic knowledge of HTML and CSS.
2. Step-by-Step Guide
CSS Grid is a 2-dimensional system that allows us to layout web elements in rows and columns. The overall container is the grid container, and the elements inside are the grid items.
To start, let's make an HTML container and add some items:
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
To make the container a grid, we use display: grid
:
.container {
display: grid;
}
To add rows and columns, we use grid-template-rows
and grid-template-columns
. These properties allow us to define the number and size of the rows and columns:
.container {
display: grid;
grid-template-columns: 200px 200px 200px;
grid-template-rows: 100px 100px;
}
The above code creates a grid with 3 columns each of 200px and 2 rows each of 100px.
3. Code Examples
Example 1: Let's look at positioning items on the grid:
.item:nth-child(1) {
grid-column: 1 / 3;
grid-row: 1 / 2;
}
In this code, the first item spans from the first to the third column line (covering two columns) and from the first to the second row line (covering one row).
Example 2: The fr
unit represents a fraction of the remaining space in the grid container.
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: 1fr 1fr;
}
This code creates a grid with three columns and two rows. The middle column will take up twice as much space as the other two.
4. Summary
In this tutorial, we've covered the basics of CSS Grid, including creating grid containers and items, defining rows and columns, and positioning items.
To further your learning, you might explore areas like grid gap, aligning and justifying items, and using auto-fill
and auto-fit
for responsive layouts. Resources like CSS Tricks and MDN Web Docs are great for this.
5. Practice Exercises
Exercise 1: Create a grid with five rows and five columns, each taking up an equal amount of space.
Exercise 2: Position an item to span from the second to the fourth column line and from the first to the third row line.
Exercise 3: Create a responsive grid that has three columns on wider screens and only one column on narrower screens.
Solutions and explanations for these exercises can be found in the CSS Grid Guide and Grid by Example. Practice makes perfect, so keep experimenting with different grid configurations to improve your mastery of CSS Grid.