Hongmu Notes
Home Language Notes css3 grid layout
Language Notes CSS

css3 grid layout

css3 grid layout

1. Overview

Grid layout (Grid) is the most powerful CSS layout solution.

It divides web pages into grids, and you can combine different grids to create various layouts. Effects that were previously only possible through complex CSS frameworks are now built into browsers.

A layout like the one pictured above is the specialty of Grid layout.

Grid layout has certain similarities with Flex layout. Both can specify the position of multiple items inside the container. However, there are important differences.

Flex layout is an axis layout, which can only specify the position of the "item" relative to the axis, and can be regarded as a one-dimensional layout. 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 as a two-dimensional 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

An area with a grid layout is called a "container". The child elements using grid positioning inside the container are called "items".

    <div>
      <div><p>1</p></div>
      <div><p>2</p></div>
      <div><p>3</p></div>
    </div>

In the above code, the outermost <div> element is the container, and the three inner <div> elements are the items.

Note: Projects can only be the top-level child elements of the container, and do not include child elements of the project. For example, the <p> element in the above code is not a project. Grid layout only takes effect on projects.

2.2 Rows and columns

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

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

2.3 Cells

The intersection area of ​​rows and columns is called a "cell".

Normally, n rows and m columns produce n x m cells. For 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, n rows have n + 1 horizontal grid lines, and m columns have m + 1 vertical grid lines. For example, there are four horizontal grid lines in three rows.

The picture above is a 4 x 4 grid with a total of 5 horizontal grid lines and 5 vertical grid lines.

3. Container properties

The properties of Grid layout are divided into two categories. One type is defined on the container and is called container properties; the other type is defined on the project and is called project properties. This part first introduces container properties.

3.1 display attribute

display: grid specifies a container to use a grid layout.

    div {
      display: grid;
    }

The picture above is the effect of display: grid.

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

    div {
      display: inline-grid;
    }

The above code specifies that the div is an inline element with a grid layout inside.

Note that after setting to grid layout, the float, display: inline-block, display: table-cell, vertical-align and column-* settings of the container sub-elements (items) will be invalid.

3.2

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

After the container specifies the grid layout, it must then divide the rows and columns. The grid-template-columns attribute defines the column width of each column, and the grid-template-rows attribute defines the row height of each row.

    .container {
      display: grid;
      grid-template-columns: 100px 100px 100px;
      grid-template-rows: 100px 100px 100px;
    }

The above code specifies a grid with three rows and three columns. The column width and row height are both 100px.

Instead of 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)repeat()

Sometimes, it is very troublesome to write the same value repeatedly, especially when there are many grids. At this time, you can use the repeat() function to simplify repeated values. The above code is rewritten as follows using repeat().

    .container {
      display: grid;
      grid-template-columns: repeat(3, 33.33%);
      grid-template-rows: repeat(3, 33.33%);
    }

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

repeat() can also repeat a pattern.

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

The above code defines 6 columns, the first and fourth columns are 100px wide, the second and fifth columns are 20px, and the third and sixth columns are 80px.

(2) auto-fill keyword

Sometimes, the size of the cell is fixed, but the size of the container is undefined. If you want each row (or column) to accommodate as many cells as possible, you can use the auto-fill keyword to indicate automatic filling.


    .container {
      display: grid;
      grid-template-columns: repeat(auto-fill, 100px);
    }

The above code indicates that each column is 100px wide, and then automatically filled until the container cannot place more columns.

(3) fr keyword

In order to conveniently express proportional relationships, grid layout provides the fr keyword (abbreviation of fraction, meaning "fragment"). If the width of two columns is 1fr and 2fr respectively, it means that the latter is twice the width of the former.

    .container {
      display: grid;
      grid-template-columns: 1fr 1fr;
    }

The above code represents two columns of the same width.

fr can be used in conjunction with absolute length units, which is very convenient.

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

The above code indicates that the width of the first column is 150 pixels, and the width of the second column is half of the third column.

(4)minmax()

The minmax() 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);

In the above code, minmax(100px, 1fr) means that the column width is not less than 100px and not greater than 1fr.

(5)auto keyword

The auto keyword indicates that the browser determines the length.

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

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

(6) Name of grid lines

In the grid-template-columns attribute and grid-template-rows attribute, you can also use square brackets to specify the name of each grid line to facilitate future reference.

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

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

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

(7) Layout example

The grid-template-columns property is very useful for web page layout. Two-column layout only requires one line of code.

    .wrapper {
      display: grid;
      grid-template-columns: 70% 30%;
    }

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);

3.3

grid-row-gap attribute,
grid-column-gap attribute,
grid-gap property

The grid-row-gap property sets the spacing between rows (row spacing), and the grid-column-gap property sets the spacing between columns (column spacing).

    .container {
      grid-row-gap: 20px;
      grid-column-gap: 20px;
    }

In the above code, grid-row-gap is used to set the row spacing, and grid-column-gap is used to set the column spacing.

The grid-gap attribute is the combined abbreviation of grid-column-gap and grid-row-gap. The syntax is as follows.

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

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

    .container {
      grid-gap: 20px 20px;
    }

If grid-gap omits the second value, the browser considers the second value to be equal to the first value.

根据最新标准,上面三个属性名的grid-前缀已经删除,grid-column-gap和grid-row-gap写成column-gap和row-gap,grid-gap写成gap。

3.4 grid-template-areas property

Grid layout allows you to specify "areas", which are composed of single or multiple cells. The grid-template-areas attribute is used to define areas.

    .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';
    }

The above code first divides 9 cells, and then names them as nine areas from a to i, corresponding to these nine cells respectively.

The writing method of merging multiple cells into one area is as follows.

    grid-template-areas: 'a a a'
                         'b b b'
                         'c c c';

The above code divides 9 cells into three areas: a, b, and c.

Below is an example layout.


    grid-template-areas: "header header header"
                         "main main sidebar"
                         "footer footer footer";

In the above code, the top is the header area, the bottom is the footer area, and the middle part is the main and sidebar.

If some areas do not need to be utilized, use "dot" (.) to indicate it.


    grid-template-areas: 'a . c'
                         'd . f'
                         'g . i';

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

注意,区域的命名会影响到网格线。每个区域的起始网格线,会自动命名为区域名-start,终止网格线自动命名为区域名-end。

比如,区域名为header,则起始位置的水平网格线和垂直网格线叫做header-start,终止位置的水平网格线和垂直网格线叫做header-end。

3.5 grid-auto-flow attribute

After the grid is divided, the child elements of the container will be automatically placed in each grid in order. The default placement order is "row first, column second", that is, fill the first row first, and then start placing the second row, which is the order of the numbers in the figure below.

This order is determined by the grid-auto-flow attribute. The default value is row, which means "row first, then column". You can also set it to column and change it to "column first, then row".

    grid-auto-flow: column;

After setting the column in the above code, the placement order becomes as shown below.

In addition to setting row and column, the grid-auto-flow attribute can also be set to row dense and column dense. These two values ​​​​are mainly used to automatically place the remaining items after certain items are assigned positions.

The following example lets item No. 1 and item No. 2 each occupy two cells, and then under the default grid-auto-flow: row situation, the following layout will be generated.

In the picture above, the position behind item 1 is empty. This is because item 3 follows item 2 by default, so it will be ranked behind item 2.

Now modify the settings and set it to row dense, which means "row first, column second", and fill it as tightly as possible with as few spaces as possible.

    grid-auto-flow: row dense;

The effect of the above code is as follows.

The image above will fill the first row first, and then the second row, so item 3 will follow item 1. Items No. 8 and No. 9 will be ranked in the fourth row.

If you change the setting to column dense, it means "column first, then row", and try to fill in the spaces.

    grid-auto-flow: column dense;

The effect of the above code is as follows.

The above image will fill the first column first, and then the second column, so item No. 3 is in the first column and item No. 4 is in the second column. Projects No. 8 and No. 9 were squeezed into the fourth column.
3.6
justify-items attribute,
align-items attribute,
place-items property

The justify-items property sets the horizontal position of the cell content (left, center, right), and the align-items property sets the vertical position of the cell content (top, middle, bottom).

    .container {
      justify-items: start | end | center | stretch;
      align-items: start | end | center | stretch;
    }

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

    start:对齐单元格的起始边缘。
    end:对齐单元格的结束边缘。
    center:单元格内部居中。
    stretch:拉伸,占满单元格的整个宽度(默认值)。
    .container {
      justify-items: start;
    }

The above code indicates that the content of the cell is left aligned, and the effect is as shown below.

    .container {
      align-items: start;
    }

The above code indicates that the content of the cell is head-aligned, and the effect is as shown below.

The place-items attribute is the combined abbreviation of the align-items attribute and the justify-items attribute.

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

Below is an example.

    place-items: start end;

If the second value is omitted, the browser considers it equal to the first value.
3.7
justify-content attribute,
align-content attribute,
place-content attribute

The justify-content property is the horizontal position of the entire content area in the container (left, center, right), and the align-content property is the vertical position of the entire content area (top, middle, 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;  
    }

These two attributes are written exactly the same and can take the following values. (The following figures all use the justify-content attribute as an example. The figures for the align-content attribute are exactly the same, except that the horizontal direction is changed to the vertical direction.)

        start - 对齐容器的起始边框。

        end - 对齐容器的结束边框。

        center - 容器内部居中。

        stretch - 项目大小没有指定时,拉伸占据整个网格容器。

        space-around - 每个项目两侧的间隔相等。所以,项目之间的间隔比项目与容器边框的间隔大一倍。

        space-between - 项目与项目的间隔相等,项目与容器边框之间没有间隔。

        space-evenly - 项目与项目的间隔相等,项目与容器边框之间也是同样长度的间隔。

place-content属性是align-content属性和justify-content属性的合并简写形式。
place-content: <align-content> <justify-content>

Below is an example.

place-content: space-around space-evenly;

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, some items are assigned positions outside the existing grid. For example, the grid only has 3 columns, but a certain item is specified in row 5. At this time, the browser will automatically generate extra grids to facilitate placement of items.

The grid-auto-columns property and the grid-auto-rows property are used to set the column width and row height of the redundant grid automatically created by the browser. They are written exactly the same as grid-template-columns and grid-template-rows. If these two properties are not specified, the browser determines the column width and row height of the new grid entirely based on the size of the cell content.

In the example below, the divided grid is 3 rows x 3 columns, but item No. 8 is specified in the 4th row and item No. 9 is specified in the 5th row.

    .container {
      display: grid;
      grid-template-columns: 100px 100px 100px;
      grid-template-rows: 100px 100px 100px;
      grid-auto-rows: 50px; 
    }

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

3.9
grid-template attribute,
grid property

The grid-template attribute is the combined abbreviation of the three attributes grid-template-columns, grid-template-rows and grid-template-areas.

The grid attribute is the combined abbreviation of the six attributes: grid-template-rows, grid-template-columns, grid-template-areas, grid-auto-rows, grid-auto-columns, and grid-auto-flow.

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

The following properties are defined on the project.
4.1
grid-column-start property,
grid-column-end property,
grid-row-start attribute,
grid-row-end property

The position of the project can be specified. The specific method is to specify the four borders of the project and which grid lines are positioned respectively.

grid-column-start属性:左边框所在的垂直网格线
grid-column-end属性:右边框所在的垂直网格线
grid-row-start属性:上边框所在的水平网格线
grid-row-end属性:下边框所在的水平网格线

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

The above code specifies that the left border of item 1 is the second vertical grid line, and the right border is the fourth vertical grid line.

In the picture above, only the left and right borders of item No. 1 are specified, and the upper and lower borders are not specified, so the default position will be used, that is, the upper border is the first horizontal grid line, and the lower border is the second horizontal grid line.

Except for item No. 1, other items have no specified positions and are automatically laid out by the browser. At this time, their positions are determined by the grid-auto-flow attribute of the container. The default value of this attribute is row, so they will be arranged "row first, then column". Readers can change the value of this attribute to column, row dense and column dense respectively to see how the positions of other items have changed.

The following example shows the effect of specifying four border positions.

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

The values of these four attributes, in addition to being specified as the grid line number, can also be specified as the name of the grid line.

    .item-1 {
      grid-column-start: header-start;
      grid-column-end: header-end;
    }

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 use the span keyword to indicate "span", that is, how many grids are spanned between the left and right borders (top and bottom borders).

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

The above code indicates that the left border of item No. 1 spans 2 grids from the right border.

This has the exact same effect as the code below.

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

Using these four attributes, if overlap of items occurs, use the z-index attribute to specify the overlapping order of items.
4.2
grid-column attribute,
grid-row attribute

The grid-column attribute is the combined abbreviation of grid-column-start and grid-column-end, and the grid-row attribute is the combined abbreviation of the grid-row-start attribute and grid-row-end.

    .item {
      grid-column: <start-line> / <end-line>;
      grid-row: <start-line> / <end-line>;
    }

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;
    }

In the above code, item-1 occupies the first row, from the first column line to the third column line.

Among these two attributes, you can also use the span keyword to indicate how many grids it spans.

    .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;
    }

In the above code, the area occupied by item-1 includes the first row + second row, and the first column + second column.

The slash and the following parts can be omitted and span a grid by default.

    .item-1 {
      grid-column: 1;
      grid-row: 1;
    }

In the above code, item-1 occupies the first grid in the upper left corner.
4.3 grid-area attribute

The grid-area attribute specifies the area in which the item is placed.

    .item-1 {
      grid-area: e;
    }

In the above code, project No. 1 is located in area e, and the effect is as shown below.

The grid-area attribute can also be used as the combined shorthand form of grid-row-start, grid-column-start, grid-row-end, and grid-column-end to directly specify the location of the item.

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

Below is an example.

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

4.4
justify-self attribute,
align-self attribute,
place-self attribute

The justify-self attribute sets the horizontal position of the cell content (left, center, right), which is exactly the same as the justify-items attribute, but only affects a single item.

The align-self attribute sets the vertical position (top, middle, and bottom) of the cell content. It is exactly the same as the align-items attribute, and it only affects a single item.

    .item {
      justify-self: start | end | center | stretch;
      align-self: start | end | center | stretch;
    }

Both properties can take the following four values.

    start:对齐单元格的起始边缘。
    end:对齐单元格的结束边缘。
    center:单元格内部居中。
    stretch:拉伸,占满单元格的整个宽度(默认值)。

Below is an example of justify-self: start.

    .item-1  {
      justify-self: start;
    }

The place-self attribute is the combined abbreviation of the align-self attribute and the justify-self attribute.


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

Below is an example.


    place-self: center center;

If the second value is omitted, the place-self attribute considers the two values to be equal.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

css positioning

css positioning Language Notes CSS

Syntax: position: static | relative | absolute | fixed | center | page | sticky Default value: static Applies to: All elements except the display attribute defined as table-column-group | table-column Inheritance: No Animation: No...
👁 119
css vh and vw adaptive

css vh and vw adaptive Language Notes CSS

In the mobile terminal, REM is used to change the root HTML, and the mobile terminal adaptation is realized through a piece of JS. This article uses pure CSS viewport units to self-adapt. Although the current compatibility is not fully acceptable, it does not prevent you from recognizing the power of vw and vh. The implementation of responsive layout relies on media queries (Media Queries). Select the width size of mainstream devices as breakpoints to target...
👁 356

Recommended reading

Resource website typecho001 template

Resource website typecho001 template Program Notes Typecho

typecho001 template template please do not modify the folder name of this template. The folder name is: typecho001 1.4 Fix the js output problem on the article page 1.3 Fix the error prompt when the plug-in is not installed Optimize the list page code output 1.2 Fix the comment function and add a custom homepage title 1.1 Fix the comment reply asymmetry function Add a separate title setting function on the homepage Add the website favicon.ico icon Add one...
👁 198
Modification of typecho paging style

Modification of typecho paging style Program Notes Typecho

Sir, times have changed! Typecho is currently the most perfect solution, because Baidu can only see the code of fixed thinking. The actual generated HTML code is breathtakingly clean and fully customized, including adding classes to the li element, adding classes to the a element, adding classes to the previous page and next page, and removing the li tags that come with typecho to express more. I can even add some text to the content inside...
👁 517
Typecho article page comment style modification

Typecho article page comment style modification Program Notes Typecho

When you need to use typecho for template development, the default comment style is ugly. Therefore, comments need to be re-output or styled. The default comment template file path is: comments.php Mainly used related variables<?php $comments->gravatar('40', ''); ?> //Avatar has two parameters, size,...
👁 388
Typecho's API for adding, deleting, modifying and querying databases

Typecho's API for adding, deleting, modifying and querying databases Program Notes Typecho

Typecho database provides a very easy-to-use API, which is not much different from the native SQL writing method. At the same time, it also handles common SQL security issues, such as SQL injection. From a practical perspective, this article introduces common scenarios for typecho to operate databases and related API usage. Table creation and deletion During the development process of Typecho plug-in, you often need to create your own table. Typecho_… mentioned above
👁 552
PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
Summary of methods for calling popular comment articles and calling latest articles in Typecho

Summary of methods for calling popular comment articles and calling latest articles in Typecho Program Notes Typecho

Typecho articles call the Typecho program. When designing a theme, the sidebar sometimes needs to call popular articles or the latest articles. We can call it directly through the script at the specified location. In this article, we will organize this method of calling articles, which can be directly called and used in templates where needed in the future. In fact, designing a theme is just that. After the static template is completed, it is called directly. The latest article calls <?php $t…
👁 295