CSS Grid Layout tutorial

The Grid is the most powerful CSS layout scheme.

It divides web pages into grids that can be arbitrarily combined to create a variety of layouts. Effects that previously could only be achieved through complex CSS frameworks are now built into browsers.Layouts like the one above are Grid layouts at their best.

A Grid layout is similar to a Flex layout in that it can specify the location of multiple items within a container. But there are also important differences.

Flex layout is an axis layout and can only specify the position of “items” against the axis, which can be considered as a one-dimensional layout. A Grid layout divides the container into “rows” and “columns”, generates cells, and then specifies the cells “where the project resides”, which can be thought of as a two-dimensional layout. The Grid layout is far more powerful than the Flex layout.

Containers and Items

Areas that use a grid layout are called containers. Inside the container, grid-positioned child elements are called “items”.

<div>
  <div><p>1</p></div>
  <div><p>2</p></div>
  <div><p>3</p></div>
</div>
Copy the code

In the code above, the outermost

element is the container, and the three

elements in the inner layer are the items.

Note: a project can only be a top-level child of the container, not a child of the project, such as the

element in the code above. Grid layout only works for projects.

Rows and columns

The horizontal areas inside the container are called rows, and the vertical areas are called columns.

In the figure above, horizontal dark areas are “rows” and vertical dark areas are “columns”.

The cell

The area where rows and columns intersect is called a cell.

Normally, n rows and m columns produce n x m cells. For example, 3 rows and 3 columns produce 9 cells.

Grid lines

The lines that divide a grid are called grid lines. The horizontal grid line divides the travel, and the vertical grid line divides the train.

Normally, row N has N + 1 horizontal grid lines and column M has M + 1 vertical grid lines, for example, row 3 has four horizontal grid lines.

The figure above shows a 4 x 4 grid with 5 horizontal and 5 vertical grid lines.