Technology Sharing

1. CSS Grid Layout Tutorial

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

CSS Grid Layout Tutorial

I. Overview

Grid is the most powerful CSS layout solution.

It divides the web page into grids, and you can combine different grids to create a variety of layouts. Previously, the effect could only be achieved through complex CSS frameworks, but now it is built into the browser.

1

The layout shown above is what Grid layout is good at.

Grid layout has some similarities to Flex layout in that both can specify the position of multiple items within a container. However, they also have important differences.

Flex layout is an axis layout, which can only specify the position of "items" on the axis.One-dimensional layoutThe Grid layout divides the container into "rows" and "columns", generates cells, and then specifies the cell where the "item is located", which can be regarded as2D layout. Grid layout is far more powerful than Flex layout.

2. Basic Concepts

Before learning Grid layout, you need to understand some basic concepts.

2.1 Containers and Projects

The area that uses grid layout is called a "container". The child elements inside the container that use grid positioning are called "items".

<div>
  <div><p>1</p></div>
  <div><p>2</p></div>
  <div><p>3</p></div>
</div>
  • 1
  • 2
  • 3
  • 4
  • 5

In the above code, the outermost<div>Elements are containers, the three inner layers<div>Elements are items.

Notice: Items can only be top-level child elements of containers and do not contain child elements of items, such as the code above<p>Elements are not items. Grid layout only works on items.

2.2 Rows and columns

The horizontal area inside a container is called a "row" and the vertical area is called a "column".

2

In the above picture, the horizontal dark areas are "rows" and the vertical dark areas are "columns".

2.3 Cells

The intersection of rows and columns is called a cell.

Under normal circumstances,nLine andmThe column will producen x mFor example, 3 rows and 3 columns will produce 9 cells.

2.4 Grid lines

The lines that divide the grid are called "grid lines". Horizontal grid lines divide rows, and vertical grid lines divide columns.

Under normal circumstances,nLinen + 1Horizontal grid lines,mListedm + 1There are vertical grid lines for three rows, for example, there are four horizontal grid lines.

3

The image above is a 4 x 4 grid with 5 horizontal grid lines and 5 vertical grid lines.

3. Container Properties

Grid layout properties are divided into two categories. One category is defined on the container, called container properties; the other category is defined on the item, called item properties. This section first introduces container properties.

3.1 display property

display: gridSpecifies a container to use a grid layout.

div {
  display: grid;
}
  • 1
  • 2
  • 3

4
The picture above isdisplay: gridofEffect

By default, container elements are block-level elements, but can also be set to inline elements.

div {
  display: inline-grid;
}
  • 1
  • 2
  • 3

The above code specifiesdivIt is an inline element that uses a grid layout.

5
The picture above isdisplay: inline-gridofEffect

Note that after setting the grid layout, the container child elements (items)floatdisplay: inline-blockdisplay: table-cellvertical-alignandcolumn-*All other settings will become invalid.

3.2 grid-template-columns property, grid-template-rows property

After the container specifies the grid layout, it is next divided into rows and columns.grid-template-columnsThe property defines the width of each column.grid-template-rowsThe row height property defines the row height of each row.

.container {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  grid-template-rows: 100px 100px 100px;
}
  • 1
  • 2
  • 3
  • 4
  • 5

The above codeSpecifies a three-row, three-column grid with column widths and row heights of100px
6
In addition to using absolute units, you can also use percentages.

.container {
  display: grid;
  grid-template-columns: 33.33% 33.33% 33.33%;
  grid-template-rows: 33.33% 33.33% 33.33%;
}
  • 1
  • 2
  • 3
  • 4
  • 5

(1)repeat()

Sometimes, writing the same value repeatedly is very troublesome, especially when there are many grids. In this case, you can userepeat()Function, simplifies repeated values. The above code usesrepeat()Rewrite as follows.

.container {
  display: grid;
  grid-template-columns: repeat(3, 33.33%);
  grid-template-rows: repeat(3, 33.33%);
}
  • 1
  • 2
  • 3
  • 4
  • 5

repeat()It accepts two parameters, the first one is the number of repetitions (3 in the above example), and the second one is the value to be repeated.

repeat()It's also okay to repeat a pattern.

grid-template-columns: repeat(2, 100px 20px 80px);
  • 1

The above codeSix columns are defined, and the width of the first and fourth columns is100px, the second and fifth columns are20px, the third and sixth columns are80px
7
(2) auto-fill keyword

Sometimes, the size of the cell is fixed, but the size of the container is uncertain. If you want each row (or column) to accommodate as many cells as possible, you can useauto-fillKeyword means autocomplete.

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, 100px);
}
  • 1
  • 2
  • 3
  • 4

The above codeIndicates the width of each column100px, and then automatically fills until the container can no longer hold any more columns.
8
Apart fromauto-fill, and a keywordauto-fit, the two behave essentially the same. This only happens when the container is wide enough to hold all the cells in one row, and the cell width is not fixed.Behavioral Differencesauto-fillThe remaining width will be filled with empty cells.auto-fitThe width of the cell will be expanded as much as possible.

(3) fr keyword

To facilitate the representation of proportional relationships, the grid layout providesfrKeyword (short for fraction). If the widths of the two columns are1frand2fr, which means the latter is twice as much as the former.

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}
  • 1
  • 2
  • 3
  • 4

The above codeRepresents two columns of equal width.
9
frCan be used in conjunction with absolute length units, which is very convenient.

.container {
  display: grid;
  grid-template-columns: 150px 1fr 2fr;
}
  • 1
  • 2
  • 3
  • 4

The above codeThis means that the width of the first column is 150 pixels, and the width of the second column is half of the width of the third column.
10

(4)minmax()

minmax()The function generates a length range, indicating that the length is within this range. It accepts two parameters, the minimum value and the maximum value.

grid-template-columns: 1fr 1fr minmax(100px, 1fr);
  • 1

In the above code,minmax(100px, 1fr)Indicates that the column width is not less than100px,no greater than1fr

(5) auto keyword

autoThe keyword indicates that the browser determines the length.

grid-template-columns: 100px auto 100px;
  • 1

In the above code, the width of the second column is basically equal to the maximum width of the cells in that column, unless the cell content is setmin-width, and this value is greater than the maximum width.

(6) Name of grid lines

grid-template-columnsAttributes andgrid-template-rowsIn the properties, you can also use square brackets to specify the name of each grid line for easy reference later.

.container {
  display: grid;
  grid-template-columns: [c1] 100px [c2] 100px [c3] auto [c4];
  grid-template-rows: [r1] 100px [r2] 100px [r3] auto [r4];
}
  • 1
  • 2
  • 3
  • 4
  • 5

The code above specifies a grid layout of 3 rows x 3 columns, so there are 4 vertical grid lines and 4 horizontal grid lines. The names of the eight lines are in square brackets.

Grid layout allows the same line to have multiple names, such as[fifth-line row-5]

(7) Layout example

grid-template-columnsThe &lt;div&gt; attribute is very useful for web page layout. A two-column layout only requires one line of code.

.wrapper {
  display: grid;
  grid-template-columns: 70% 30%;
}
  • 1
  • 2
  • 3
  • 4

The above code sets the left column to 70% and the right column to 30%.

The traditional twelve-grid layout is also easy to write.

grid-template-columns: repeat(12, 1fr);
  • 1

3.3 grid-row-gap property, grid-column-gap property, grid-gap property

grid-row-gapThe property sets the spacing between lines (line spacing).grid-column-gapThe property sets the spacing between columns (column spacing).

.container {
  grid-row-gap: 20px;
  grid-column-gap: 20px;
}
  • 1
  • 2
  • 3
  • 4

The above codemiddle,grid-row-gapUsed to set line spacing,grid-column-gapUsed to set the spacing between columns.
11
grid-gapThe attribute isgrid-column-gapandgrid-row-gapThe combined abbreviation of is as follows.

grid-gap: <grid-row-gap> <grid-column-gap>;
  • 1

Therefore, the above CSS code is equivalent to the following code.

.container {
  grid-gap: 20px 20px;
}
  • 1
  • 2
  • 3

ifgrid-gapThe second value is omitted and the browser considers the second value equal to the first value.

According to the latest standards, the above three attribute namesgrid-The prefix has been removed.grid-column-gapandgrid-row-gapWrittencolumn-gapandrow-gapgrid-gapWrittengap

3.4 grid-template-areas Property

Grid layout allows you to specify "areas", which can consist of a single cell or multiple cells.grid-template-areasAttributes are used to define regions.

.container {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  grid-template-rows: 100px 100px 100px;
  grid-template-areas:
    'a b c'
    'd e f'
    'g h i';
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

The above code first divides 9 cells and then names themaarriveiThe nine areas correspond to these nine cells respectively.

The following is how to merge multiple cells into one area.

grid-template-areas:
  'a a a'
  'b b b'
  'c c c';
  • 1
  • 2
  • 3
  • 4

The above code divides 9 cells intoabcThree areas.

Below is an example layout.

grid-template-areas:
  'header header header'
  'main main sidebar'
  'footer footer footer';
  • 1
  • 2
  • 3
  • 4

In the above code, the top is the header areaheader, the bottom is the footer areafooter, and the middle part ismainandsidebar

If some areas do not need to be utilized, use "points" (.)express.

grid-template-areas:
  'a . c'
  'd . f'
  'g . i';
  • 1
  • 2
  • 3
  • 4

In the above code, the middle column is a dot, which means that the cell is not used or does not belong to any area.

Note that the naming of the region will affect the grid lines. The starting grid line of each region will be automatically named区域名-start, the ending grid line is automatically named区域名-end

For example, the region name isheader, then the horizontal and vertical grid lines at the starting position are calledheader-start, the horizontal and vertical grid lines at the end are calledheader-end

3.5 grid-auto-flow property

After dividing the grid, the sub-elements of the container will be automatically placed in each grid in order. The default placement order is "rows first, then columns", that is, fill the first row first, and then start to place the second row, which is the order of the numbers in the figure below.
12
This order is determined bygrid-auto-flowAttributes, the default value isrow, which means "rows first, columns later". You can also set it tocolumn, it becomes "columns first, rows later".

grid-auto-flow: column;
  • 1

The above codealready setupcolumnAfter that, the placement order becomes as shown below.
13
grid-auto-flowIn addition to setting the propertyrowandcolumn, and can also be set torow denseandcolumn denseThese two values ​​are mainly used to determine how to automatically place the remaining items after certain items have specified their positions.

The following exampleLet item 1 and item 2 occupy two cells each, and then in the defaultgrid-auto-flow: rowIn this case, the following layout will be generated.
14
In the above picture, the position after item 1 is empty. This is because item 3 follows item 2 by default, so it will be placed after item 2.

Now modify the settings torow dense, which means "rows first, columns later", and fills the space as tightly as possible with no spaces.

grid-auto-flow: row dense;
  • 1

The above codeThe effect is as follows.
15
The image above would fill the first row first, then the second row, so item 3 would be right after item 1. Items 8 and 9 would go to the fourth row.

If you change the setting tocolumn dense, which means "columns first, rows later", and try to fill in as many spaces as possible.

grid-auto-flow: column dense;
  • 1

The above codeThe effect is as follows.
16
The above diagram will fill the first column first, then the second column, so item 3 is in the first column and item 4 is in the second column. Items 8 and 9 are squeezed into the fourth column.

3.6 justify-items property, align-items property, place-items property

justify-itemsThe property sets the horizontal position of the cell content (left, center, right).align-itemsProperty sets the vertical position (top, center, bottom) of the cell content.

.container {
  justify-items: start | end | center | stretch;
  align-items: start | end | center | stretch;
}
  • 1
  • 2
  • 3
  • 4

These two properties are written exactly the same way and can take the following values.

  • start: Align the starting edge of the cell.
  • end: Aligns to the end edge of the cell.
  • center: The cell is centered inside.
  • stretch: stretch to fill the entire width of the cell (default value).
.container {
  justify-items: start;
}
  • 1
  • 2
  • 3

The above codeIt means that the content of the cell is left-aligned, as shown in the following figure.
17

.container {
  align-items: start;
}
  • 1
  • 2
  • 3

The above codeIt means that the content header of the cell is aligned, and the effect is as shown below.
18
place-itemsThe attribute isalign-itemsAttributes andjustify-itemsA shorthand form for combining attributes.

place-items: <align-items> <justify-items>;
  • 1

Below is an example.

place-items: start end;
  • 1

If the second value is omitted, the browser considers it equal to the first value.

3.7 justify-content property, align-content property, place-content property

justify-contentThe property is the horizontal position of the entire content area in the container (left, center, right).align-contentThe property is the vertical position of the entire content area (top, center, bottom).

.container {
  justify-content: start | end | center | stretch | space-around | space-between | space-evenly;
  align-content: start | end | center | stretch | space-around | space-between | space-evenly;
}
  • 1
  • 2
  • 3
  • 4

These two properties are written in exactly the same way and can take the following values.justify-contentTake attributes as an example,align-contentThe graph of the properties is exactly the same, except that the horizontal orientation is changed to vertical.)

  • start - the starting border of the container to align to.
    19
  • end - Aligns to the container's end border.
    20
  • center - Centered inside the container.
    21
  • stretch - When the item size is not specified, it stretches to occupy the entire grid container.
    22
  • space-around - The space around each item is equal. So, the space between items is twice as large as the space around the container border.
    23
  • space-between - Items are spaced equally from one another, with no space between items and the container border.
    24
  • space-evenly - The spacing between items is equal, and the spacing between items and the container border is also the same length.
    25
    place-contentThe attribute isalign-contentAttributes andjustify-contentA shorthand form for combining attributes.
place-content: <align-content> <justify-content>;
  • 1

Below is an example.

place-content: space-around space-evenly;
  • 1

If you omit the second value, the browser assumes that the second value is equal to the first value.

3.8 grid-auto-columns property, grid-auto-rows property

Sometimes, the specified position of some items is outside the existing grid. For example, the grid has only 3 columns, but an item is specified in the 5th row. In this case, the browser will automatically generate extra grids to place the items.

grid-auto-columnsAttributes andgrid-auto-rowsThe properties are used to set the column width and row height of the extra grid that the browser automatically creates. They are written in the same way asgrid-template-columnsandgrid-template-rowsExactly the same. If these two attributes are not specified, the browser determines the column width and row height of the newly added grid based entirely on the size of the cell content.

The following exampleInside, the grid is divided into 3 rows x 3 columns, but item number 8 is assigned to the 4th row and item number 9 is assigned to the 5th row.

.container {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  grid-template-rows: 100px 100px 100px;
  grid-auto-rows: 50px;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

The above code specifies that the newly added row height is uniformly 50px (the original row height is 100px).

26

3.9 grid-template property, grid property

grid-templateThe attribute isgrid-template-columnsgrid-template-rowsandgrid-template-areasA shorthand form for the concatenation of these three properties.

gridThe attribute isgrid-template-rowsgrid-template-columnsgrid-template-areasgrid-auto-rowsgrid-auto-columnsgrid-auto-flowA combined shorthand form of these six properties.

From the perspective of readability and ease of writing, it is recommended not to merge attributes, so these two attributes will not be introduced in detail here.

IV. Project Properties

The following properties are defined on the project.

4.1 grid-column-start property, grid-column-end property, grid-row-start property, grid-row-end property

The position of the item can be specified by specifying which grid lines the four borders of the item should be positioned on.

  • grid-column-startProperty: The vertical grid line where the left border is located
  • grid-column-endProperty: The vertical grid line where the right border is located
  • grid-row-startProperty: The horizontal grid line where the top border is located
  • grid-row-endProperty: The horizontal grid line where the bottom border is located
.item-1 {
  grid-column-start: 2;
  grid-column-end: 4;
}
  • 1
  • 2
  • 3
  • 4

The above codeSpecifies that the left border of item 1 is the second vertical grid line, and the right border is the fourth vertical grid line.
27
In the above figure, only the left and right borders of item 1 are specified, and the top and bottom borders are not specified, so the default position will be used, that is, the top border is the first horizontal grid line, and the bottom border is the second horizontal grid line.

Except for item 1, the other items have no specified position and are automatically laid out by the browser. Their positions are determined by the container.grid-auto-flowThe default value of this property isrow, so it will be arranged "rows first, columns later". Readers can change the value of this attribute tocolumnrow denseandcolumn denseto see how the positions of other projects have changed.

The following exampleIt is the effect of specifying the positions of the four borders.

.item-1 {
  grid-column-start: 1;
  grid-column-end: 3;
  grid-row-start: 2;
  grid-row-end: 4;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

28
The values ​​of these four properties can be specified as the grid line number or the grid line name.

.item-1 {
  grid-column-start: header-start;
  grid-column-end: header-end;
}
  • 1
  • 2
  • 3
  • 4

In the above code, the positions of the left and right borders are specified as the names of the grid lines.

The values ​​of these four attributes can also be usedspanKeyword, meaning "span", that is, how many grids the left and right borders (top and bottom borders) span.

.item-1 {
  grid-column-start: span 2;
}
  • 1
  • 2
  • 3

The above codeThis means that the left border of item 1 spans 2 grids from the right border.
29
This is similar toThe following codeThe effect is exactly the same.

.item-1 {
  grid-column-end: span 2;
}
  • 1
  • 2
  • 3

Using these four attributes, if there is an overlap of items, usez-indexProperty specifies the overlapping order of items.

4.2 grid-column property, grid-row property

grid-columnThe attribute isgrid-column-startandgrid-column-endThe combined abbreviation ofgrid-rowThe attribute isgrid-row-startAttributes andgrid-row-endThe combined abbreviation of .

.item {
  grid-column: <start-line/ <end-line>;
  grid-row: <start-line/ <end-line>;
}
  • 1
  • 2
  • 3
  • 4

Below is an example.

.item-1 {
  grid-column: 1 / 3;
  grid-row: 1 / 2;
}
/* 等同于 */
.item-1 {
  grid-column-start: 1;
  grid-column-end: 3;
  grid-row-start: 1;
  grid-row-end: 2;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

In the above code, the projectitem-1Occupies the first row, from the first column line to the third column line.

Of these two attributes, you can also usespanKeyword indicating how many grids to span.

.item-1 {
  background: #b03532;
  grid-column: 1 / 3;
  grid-row: 1 / 3;
}
/* 等同于 */
.item-1 {
  background: #b03532;
  grid-column: 1 / span 2;
  grid-row: 1 / span 2;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

The above codeProjectitem-1The occupied area includes the first row + the second row, the first column + the second column.
30
The slash and the part following it can be omitted, and by default it spans one grid.

.item-1 {
  grid-column: 1;
  grid-row: 1;
}
  • 1
  • 2
  • 3
  • 4

In the above code, the projectitem-1Occupies the first grid in the upper left corner.

4.3 The grid-area property

grid-areaThe property specifies in which area the item is placed.

.item-1 {
  grid-area: e;
}
  • 1
  • 2
  • 3

The above codeAmong them, Project No. 1 is located ineArea, the effect is as shown below.
31
grid-areaAttributes can also be used asgrid-row-startgrid-column-startgrid-row-endgrid-column-endA combined shorthand form that directly specifies the location of the item.

.item {
  grid-area: <row-start> / <column-start> / <row-end> / <column-end>;
}
  • 1
  • 2
  • 3

Here is aexample

.item-1 {
  grid-area: 1 / 1 / 3 / 3;
}
  • 1
  • 2
  • 3

4.4 justify-self, align-self, and place-self properties

justify-selfProperty sets the horizontal position of the cell content (left, center, right).justify-itemsThe properties are used exactly the same way, but only on a single item.

align-selfThe property sets the vertical position (top, center, bottom) of the cell content.align-itemsThe usage of the attribute is exactly the same and only applies to a single project.

.item {
  justify-self: start | end | center | stretch;
  align-self: start | end | center | stretch;
}
  • 1
  • 2
  • 3
  • 4

Both attributes can take the following four values.

  • start: Align the starting edge of the cell.
  • end: Aligns to the end edge of the cell.
  • center: The cell is centered inside.
  • stretch: stretch to fill the entire width of the cell (default value).

Below isjustify-self: startexample of.

.item-1 {
  justify-self: start;
}
  • 1
  • 2
  • 3

32
place-selfThe attribute isalign-selfAttributes andjustify-selfA shorthand form for combining attributes.

place-self: <align-self> <justify-self>;
  • 1

Below is an example.

place-self: center center;
  • 1

If the second value is omitted,place-selfThe property considers the two values ​​equal.