All the tricks and tricks are just a matter of inches.

Almost as soon as we entered the field of front-end development, we were constantly exposed to different layout techniques. CSS layout technology continues to evolve, from the common float to the tabular layout to the popular Flex layout. Grid, as a product of CSS3, is closer to the layout strategy used by web designers. Learning and making good use of grid can help us avoid many layout problems.

While grid layout has many benefits, it is not easy to learn because there are so many attributes to set the layout, including 17 that apply to the parent container alone, plus 10 that apply to child elements, and different ways to value those attributes. That’s a lot of weight to put on your memory. So how do you digest so many attributes and uses in such a short time? In the following article, I will share my own learning strategies for each of these 27 attributes and their respective uses, in the hope that they will help you learn.

The path to the layout

CSS as a web layout design language, its core design ideas must comply with the relevant domain knowledge. Grid layout is a two-dimensional layout structure, which is formed by two groups of intersecting grid lines. Web designers can use these structured structures of rows and columns to lay out design elements. When defining a grid layout structure, we need to describe the main frame structure to be laid out on the parent container. To describe this framework structure, we need to name its basic constituent elements. The components of a grid layout can be summarized as the following concepts:

  • The row line: line line
  • The column line: column line
  • Track: Grid track, i.e. the area formed between lines or lines, for placing child elements
  • Gap: Unusable area of grid space, line to line, or line to line, used to separate elements
  • Cell: an area separated by rows and columns for placing child elements in a grid cell
  • Area: A grid area consisting of one or more grid cells for placing child elements

Keeping these concepts in mind is the foundation for mastering and applying grid layouts.

Build the method of

The key to mastering a skill is to find the basics and then practice them so that you can reduce decision time later on. Therefore, this part mainly introduces some common routines in the process of grid layout construction. The problem here is how to use the most basic rules to build an ideal layout model. When it comes down to layout, there are only two types of page elements to deal with: parent containers and child elements. The former is mainly used to set the basic layout framework, equivalent to the design blueprint in architecture, while the latter is used for personalized layout adjustments. So I personally summarized the pattern in grid layout: there are three steps for setting the parent container elements: frame, space, and align, and two steps for child elements: place and align. I refer to them collectively as **”32 Ways to Build “**.

In this section, I will focus on all 27 attribute names used in grid layout, and the value logic will be uniformly described in the last section.

The parent container

Set the framework

The first step in setting up the grid layout of the parent container is to set the box model of the parent container to grid, which triggers the rendering engine’s grid layout algorithm.

.parent {
	display: grid;
}
Copy the code

Next we begin to prepare the “line drawing”, which is the base line for setting up the desired rows and columns. These lines will form the base template for our subsequent layout. In the line drawing process, we need to set the row and column dimensions separately. If you need to draw a few lines, set a few values (not including borders). The value is the size of the track. Here I first draw a 3×3 grid frame, the code is as follows:

.parent {
	display: grid;
	grid-template-rows: 100px 100px 100px;
	grid-template-columns: 100px 100px 100px;
}
Copy the code

Here you can also choose to abbreviate both rows and columns, separated by / :

.parent {
	display: grid;
	grid-template: 100px 100px 100px / 100px 100px 100px;
}
Copy the code

After drawing the lines, we can choose to name the lines and the area formed between them, so that we can use these names directly in the future, so that we can locate the child elements.

.parent {
	display: grid;
	grid-template-areas: "a a b"
	                     "c d e"
	                     "c d ."
}
Copy the code

The above two steps can also be set in abbreviated form, the code is as follows:

.parent {
  	display: grid;
  	grid-template: "a a b" 101px
  	               "c d e" 102px
  	               "c d ." 103px / 104px 105px 105px
}
Copy the code

Since grid-template is a tricky way to write row and column names and region names at the same time, I set the values to regular increasing numbers for ease of explanation. (101, 102,103) set grid-template-rows and (104,105,106) set grid-template-columns.

At this point, we can say that more than half of the work we need to do has been done.

Set interval

The spacing (gap) setting is optional in actual development, depending on the requirements of the web design. If you need to set the spacing between grid lines, we can set the spacing between row and column dimensions separately. The following code sets the spacing for each row and column by 10px:

.parent {
	display: grid;
	grid-template: 100px 100px 100px / 100px 100px 100px;
	grid-row-gap: 10px;
	grid-column-gap: 10px;
}
Copy the code

If abbreviated, the above code can be simplified to:

.parent {
	display: grid;
	grid-template: 100px 100px 100px / 100px 100px 100px;
	grid-gap: 10px 10px;
}
Copy the code

The effect is as follows:

Looking for alignment

With the previous two steps, our grid layout framework is almost complete. Each child element occupies a grid region by default. In the parent container, the last step is to find alignment if needed. The so-called alignment can be divided into internal and external (the former for the children of each grid region, and the latter for the grid region itself). In addition, rows and columns (more technically, main axis and cross Axis) have two dimensions each, making up four ways to set alignment.

Let’s start with how each child element is aligned relative to the interior of the grid region:

.parent {
	display: grid;
	grid-template: 100px 100px 100px / 100px 100px 100px;
	grid-gap: 10px 10px;
	justify-items: center;
	align-items: center;
}
Copy the code

In the code above I have centered the row and column directions so that the child elements in each grid region behave identically with respect to their respective regions and are evenly arranged. You can see the effect as shown below:

Let’s look at another situation:

.parent {
	display: grid;
	width: 500px;
	height: 500px;
	grid-template: 100px 100px 100px / 100px 100px 100px;
	grid-gap: 10px 10px;
	justify-content: space-between;
	align-content: center;
}
Copy the code

Sometimes the size of the grid is not enough to cover the entire size of the parent container. For example, in the example above, the entire parent container is 500px by 500px, but we only have 300px by 300px grid area, so we need to specify the processing rules for the extra space. Context-content and align-content are the properties used to solve this problem in the row and column directions, respectively. They will set the alignment in the parent container for each grid region.

Justify and align were somewhat confusing in orientation, so my trick to remember was to justify two conflations, justify Row and Aligncolumn, which were of similar length. If you have a better way to remember, let me know in the comments.

Child elements

After setting up the basic framework on top of the parent container, for most of the molecular elements, the layout is fine. For partial molecular elements, can be fine-tuned according to demand. If you want to make layout tweaks on child elements, you usually need to do the following two steps: place and find alignment.

Pendulum position

Just like in chess, for the arrangement of child elements, we need to specify where to place them. To determine the location, use the line name and region name previously specified in the parent container. One way is to specify the region for the child element directly by setting the start row, end row, start column, and end column, and the other way is to specify the region name.

/* Specifies the start row, end row, start column, end column */
.child:first-child {
    grid-row-start: 1;
    grid-row-end: 2;
    grid-column-start: 1;
    grid-column-end: 3;
    background: red;
}

/* Use the abbreviation */
.child:nth-child(2) {
	grid-row: 2/3;
	grid-column: 2/4;
	background: yellow;
}

/* Directly specify the locale name */
.child:nth-child(3) {
	grid-area: i;
	background: green;
}
Copy the code

This code looks like this:

A more flexible way to set the position is to specify the number of rows and columns to span. The keyword span is used to control the number of rows or columns to span at a time.

.child-nth-child(3) {
  grid-row: 2/3;
  grid-column: span 2;
}
Copy the code

Looking for alignment

Similar to the alignment set in the parent container, we can align individual child elements by row and column attributes:

/* Column alignment */
.child:nth-child(1) {
  align-self: end;
}

/* Line alignment */
.child:nth-child(2) {
  justify-self: end;
}

/* Use the abbreviation */
.child:nth-child(3) {
  place-self: center center;
}
Copy the code

* Implicit grid

Flexibility is one of the advantages of grid layout. In addition to manually specifying the frame structure mentioned above, grid layout also has a mechanism for automatic layout. This mechanism is called “implicit grid layout” **. The layout algorithm automatically generates an implicit grid when we place child elements outside the area defined by the grid, or when there are so many factor elements that more grid lines are needed. By default, the size of these implicit grids also varies depending on the content size, and we can control the size of implicit grids using the grid-auto-rows and grid-Auto-columns properties. Consider the following example:

<div class="parent">
  <div class="child" style="background: red"></div>
  <div class="child" style="background: yellow"></div>
  <div class="child" style="background: green"></div>
</div>
Copy the code
.parent {
  display: grid;
  grid-auto-rows: 100px;
  grid-auto-columns: 100px;
}
Copy the code

By manually setting the implicit grid size to 100×100 in the parent container, the effect is as follows:

.child:first-child {
    grid-row-start: 1;
    grid-row-end: 2;
    grid-column-start: 1;
    grid-column-end: 3;
    background: red;
}
Copy the code

With grid size control, we also need position control. By default, child elements are filled with rows first, and new implicit rows are generated when the container size is insufficient. To change this default behavior, we need to control it using the grid-auto-flow property:

.parent {
  display: grid;
  grid-auto-rows: 100px;
  grid-auto-columns: 100px;
  grid-template-areas: "a b c" "d e f" "g h i";
  grid-auto-flow: column;
}
Copy the code

The values of

After introducing all the grid layout attributes, let’s talk about the value strategy for the various attributes.

The size of the

In the CSS, we usually use units such as PX and EM to set the property size. For flexible layout requirements, percentages are also commonly used. These units seem adequate for ordinary work. However, in order to make the layout more flexible, a new unit, FR, was introduced in the grid layout. Fr is an abbreviation of the word fraction, which means the fraction ratio of the remaining space in a container. Consider the following example:

.parent {
  height: 100px;
  display: grid;
  grid-template-columns: 100px 1fr 100px;
}
Copy the code

We easily achieved a fixed width on both sides and an adaptive middle by setting the layout frame 100px 1FR 100px.

If you want to implement a proportional layout structure, you can also use multiple values of FR:

.parent {
  width: 400px;
  height: 100px;
  display: grid;
  grid-template-rows: 100px 1fr 100px;
  grid-template-columns: 1fr 1fr 2fr;
  grid-template-areas: "a b c"
}
Copy the code

You can see that the ratio between regions A, B, and C is “1:1:2”.

In addition to the adaptive units mentioned above, max-content and min-content keywords can also be used in grid layouts for adaptive purposes. To understand these two keywords, it is first necessary to understand the concepts of intrinsic size and extrinsic size. First, extrinsic size. Its relative value is the attribute value corresponding to the parent container. If the parent is 100px wide and the child is set to 20%, its width is 100px * 20% = 20px. Intrinsic size is introduced in CSS3 to calculate the intrinsic size relative to the element’s own size. Max-content and min-content are attribute values computed relative to the element’s own content block.

Min-content, as the name implies, is the minimum width set based on the element’s content. In English sentences, it is usually the length of the longest word, while in Chinese, it is the length of a word. Take this example:

.parent {
  display: grid;
  grid-template-columns: auto min-content auto;
}
Copy the code

As you can see, the width of the middle grid is equal to the length of the word scq000.

Corresponding to min-content, max-content sets the size to the maximum width that the content size can reach. Let’s change our code to the following:

.parent {
  display: grid;
  grid-template-columns: auto max-content auto;
}
Copy the code

With these two property values, we can easily make the layout area adapt to the content.

function

Function is an effective tool to avoid repetitive work, and provides some common CSS functions in grid layout to facilitate our work.

The first one is the function minmax. In the process of setting up the grid frame, we always set a minimum value and a maximum value for the adaptive grid area. This function is used to achieve this purpose.

.parent {
    display: grid;
    grid-template-columns: 100px minmax(100px, 200px) 100px;
}

/* The most common case is to set only the minimum and not the maximum */
.parent {
    display: grid;
    grid-template-columns: 100px minmax(100px, auto) 100px;
}
Copy the code

Using this function to set the grid layout can be very adaptive, in the process of page scaling can also ensure the stability of the layout.

Another useful function is fit-content, which is actually short for min(maximum size, Max (minimum size, argument)) to shrink the element width to the content width. In plain English, this function takes up as little space as possible. If the width of the content is less than the length set in fit-Content, then the actual child element width is the content width. If the content width exceeds the length set in fit-Content, the actual child element width is that length. Here are two examples:

.parent {
    display: grid;
    grid-template-rows: auto fit-content(200px) auto;
}
Copy the code

If the length in the first sentence exceeds 200px, the width of the middle grid should be 200px. In the second example, the width of the content is less than 200px, so the width of the middle grid is the width of the sentence.

Finally, the repeat function is used to set the spacing of frames in batches. This function takes two parameters, the first parameter controls the number of loops and the second parameter controls the spacing. Let’s rewrite the above example with this function:

.parent {
	display: grid;
	grid-template-rows: 100px 100px 100px;
	grid-template-columns: 100px 100px 100px;
}
/* Overwrite */ with the repeat function
.parent {
	display: grid;
	grid-template-rows: repeat(3, 100px);
	grid-template-columns: repeat(3, 100px);
}
Copy the code

In addition to setting the number of grids using a digital display, the first parameter automatically allocates space using the auto-fit and auto-fill keywords. In general, these two keywords are used to similar effect, the only difference is the free space allocation rules. The difference can be seen with minmax functions, as shown in the following two examples:

.parent {
	display: grid;
	width: 500px;
	height: 100px;
	grid-gap: 10px;
	grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}

.parent {
	display: grid;
	width: 500px;
	height: 100px;
	grid-gap: 10px;
	grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
}
Copy the code

In a single-row layout, if there is free space, Auto-fit will distribute it evenly among all child elements, while Auto-fill will automatically create blank columns.

named

When we created the grid layout framework, we specified the basic layout structure by “drawing lines”. By default, grid layouts name each grid line in the same order as they are written: left to right and top to bottom. Assuming we specify a grid layout structure of 3×3, including border lines produces 4+4=8 lines.

.parent {
  display: grid;
  grid-template-rows: [row-a] 100px [row-b] 100px [row-c] 100px [row-d];
}
Copy the code

alignment

Alignment is an indispensable step in the layout process, and its value is specified by existing keywords. The keywords used for grid alignment include start, Center, end and stretch. The default value is “stretch”, so by default, the sub-elements of the grid will fill as much of the grid area as possible, so it is not possible to use this keyword when writing code. Moving on to common alignment strategies, keep in mind that the attribute justify-* and align-* control the horizontal and vertical directions, respectively, and the value of the attribute controls the alignment position. Start, Center, and end correspond to the first, middle, and last three positions respectively.

.parent {
  display: grid;
}
.child:first-child {
  justify-self: start;
}
.child:first-child {
  justify-self: center;
}
.child:first-child {
  justify-self: end;
}
Copy the code

* to arrange

Going back to the implicit grid, the implicit arrangement is set by specifying grid-auto-flow. It only has three rows, column and Dense. Row and column, which are row first and column first, were introduced in the properties section above. We are going to introduce dense. In general, the row or column is filled in order, and if space is insufficient, the row or column is broken. With the dense attribute, free space is used as much as possible. Consider this code:

.parent {
  display: grid;
  grid-template-columns: repeat(3, 100px);
}
Copy the code
<div class="parent">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
  <div class="child">5</div>
</div>
Copy the code

By default, it looks like this:

When we use our dense value, we are in “dense” mode, using as much free space as possible.

.parent {
	display: grid;
	grid-auto-flow: row dense;
	/* Our dense */ is dense
	grid-auto-flow: dense;
}
Copy the code

So, it looks like this:

conclusion

In this article, I disassemble and classify all grid layout related knowledge points, hoping to provide you with a more systematic use of grid layout guidance method. In practice, following the “32 build method “can save a lot of thinking and decision-making time. In addition, because this article information density may be relatively large, I hope you can review more, and practice with examples several times, so that in the actual work can be like a duck to water. Finally, a mind map is provided to help you understand all the important points of this article.

Recommended reading

grid.malven.co/

www.w3.org/TR/css-alig…

medium.com/@patrickbro…

www.zhangxinxu.com/wordpress/2…

Css-tricks.com/difference-…

Drawing debugging tool: www.mozilla.org/en-US/firef…

— This article was published on personal public account, please indicate the source of reprint —