Skip to main content
Practice

Grid

A web page is like a large canvas.

Just as you decide how to apply colors and where to place drawings when creating a picture, you also need to decide where to place elements when building a web page.

CSS Grid was introduced to solve the complex problem of layout arrangement as web services advanced.


Basic Structure and Features of Grid

CSS Grid structures the layout as a Grid similar to a chessboard.

On a chessboard, there are several squares, and chess pieces are placed on each square.

CSS Grid works similarly. It divides a web page into multiple areas and freely places desired elements in each area.


Basic Grid Structure

A Grid consists of a Grid Container that holds the grid items and the Grid Items themselves.

  • Grid Container: Represents the entire grid you will create.

  • Grid Item: Each item placed within the grid.


Creating a Simple Grid Structure

CSS
.container {
display: grid; /* Grid container */
}

.item {
/* Grid item */
gap: 10px; /* Space between items */
grid-column: 1 / 3; /* Span from column 1 to column 3 */
grid-row: 1 / 2; /* Span from row 1 to row 2 */
}

In the above code, elements with the .container class become the Grid Container, and the elements within it become Grid Items.


Key Grid Properties

When constructing layouts using Grid, you utilize the following properties.


grid-template-columns, grid-template-rows

The grid-template-axis properties allow you to define how many columns and rows the container will be divided into.

CSS
.container {
display: grid; /* Grid container */
grid-template-columns: 100px 200px 100px; /* 3 columns with widths 100px, 200px, and 100px respectively */
grid-template-rows: 50px 50px; /* 2 rows with heights 50px each */
}

The above code creates a grid divided into 3 columns and 2 rows.


grid-column, grid-row

The grid-axis properties specify in which column or row the item will be placed. You can define the start and end points.

CSS
.item {
grid-column: 1 / 3;
grid-row: 1 / 2;
}

The above code specifies that the grid item will span from column 1 to column 3, and from row 1 to row 2.


Follow the highlighted parts in the code to apply the properties.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.