Complete Guide to parsing grid layout in CSS

Time:2020-2-19

Grid is a system based on two-dimensional grid layout. With it, we can easily realize the complex layout in the past without any usefloat , inline-block , positionThese are essentially hack’s methods.

CSS grid layout is good at dividing a page into several main areas, and defining the size, location, hierarchy and other relationships of these areas (provided that HTML generates these areas).

It’s like a table, and grid layout allows us to align elements by row or column. However, in layout, grid is more likely or simpler than table.

Grid layout concept

Before learning, you need to understand the following grid concepts.

Grid tracks

A grid track is the space between two grid lines. They use attributesgrid-template-columnsandgrid-template-rowsDefined in the grid.

In the picture above, there are two rows and three columns. One row or column is called track.

Grid lines

UseGridLayout creates gridlines when rails are defined in an explicit grid.

Gridlines can be addressed with their numbers. In left to right languages,Nomad 1Will be on the left side of the mesh,Line 1It will be on top of it. Line numbers follow the document’s write mode, so in right to left languages,Nomad 1The row is to the right of the grid. The following image shows the line number of the grid, assuming the language is left to right.

 

Grid cell

stayGridIn the layout, the network cell is the smallest cell in the CSS grid. It’s a space between four gridlines, much like a table cell.

 

Grid areas

A grid area is a rectangular area in a grid consisting of one or more grid cells. In essence, the grid region must be rectangular. For example, it is not possible to create a T-shaped or L-shaped mesh region.

 

Grid spacing (gutters)

Grid spacing is the spacing between grid tracks, which can be determined bygrid-column-gapgrid-row-gapCreated in grid layout.

 

Use grid layout

Similar to flex, to use a grid layout, you first need to have a container that willdisplaySet togridYou get a grid container. The sub item of the container is grid items, which is similartableMediumtd, but more flexible.

float , clear, andvertical-alignElement has no effect on the grid container.

Properties on container

Grid template

After creating the grid container, we can define how many rows and columns there are in the grid, and the size of each row and column.

grid-template-rows

We usegrid-template-rowsTo explicitly define how many rows the grid has. It can take the following values:

noneKeyword to indicate an ambiguous grid. All rows and their sizes will begrid-auto-rowsProperty is implicitly specified.

Length size of non negative valueSuch aspx, em, vwetc.

Percentage: relative to the grid container, if it isinline-grid, the percentage will be considered asauto

flex: non negative, in unitsfrTo define the elasticity coefficient of the grid orbit size. Each definesflexThe remaining free space is allocated proportionally to the

max-contentKey, which means that the grid track is occupied by the largest content of grid items

min-contentKeyword, indicating that the grid track is occupied by the largest and smallest content of grid items

autoIf the grid orbit is the largest, it is equivalent tomax-content, is the minimum, equivalent tomin-content

grid-template-columns

Its sumgrid-template-rowsSimilarly, one is to set grid rows and the other is to set grid columns.


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


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

 

Functions available in Grid

In grid layout, we can also use the following three functions

repeat()

repeatFunctions can express a large number of repeated line expressions in a more concise way.

For example, abovegrid-template-columns: 1fr 1fr 1fr;We can writerepeat(3, 1fr)。 Its first parameter is the number of repetitions, which can beauto-fillandauto-fit

auto-fill

If the container has an explicit or maximum size, the number of repetitions is the maximum possible positive integer and does not cause the mesh to overflow its mesh container. If any number of repetitions overflows, the number of repetitions is 1.

auto-fit

Andauto-fillThe behavior of is the same, except that any empty duplicate tracks collapse after the grid item is placed.


#container {
  display: grid;
  grid-template-columns: repeat(2, 50px 1fr) 100px;
  grid-gap: 5px;
  box-sizing: border-box;
  height: 200px;
  width: 100%;
  background-color: #8cffa0;
  padding: 10px;
}

#container > div {
  background-color: #8ca0ff;
  padding: 5px;
}

 

minmax()

A closed interval of long and wide range is defined. It takes two parameters, minimum and maximum. It returns the value in this interval.

asminmax(max-content, 300px), maximum cannot be greater than300px

minmax(200px, 1fr)Minimum cannot be less than200px

fit-content()

It is equivalent tomin(maximum size, max(minimum size, argument))。 Parameters can be length values and percentages.

It takes a maximum value from the minimum value and parameters of the content, and then a minimum value from the maximum value of the content.

That is to say, when the content is small, it takes the length of the content. If the content is large and the content length is greater than the parameter length, it takes the parameter length.

grid-template-areas

This attribute grid block requires andgrid-areaIn combination, its value can benoneandCharacter string

For a string, a row is generated for each given string, and a column is generated for each cell separated by a space in a string. Multiple cells with the same name that span adjacent rows or columns are called grid areas. Non rectangular grid blocks are not valid.


#page {
  display: grid;
  width: 100%;
  height: 250px;
  grid-template-areas: "head head"
                       "nav  main"
                       "nav  foot";
  grid-template-rows: 50px 1fr 30px;
  grid-template-columns: 150px 1fr;
}

#page > header {
  grid-area: head;
  background-color: #8ca0ff;
}

#page > nav {
  grid-area: nav;
  background-color: #ffa08c;
}

#page > main {
  grid-area: main;
  background-color: #ffff64;
}

#page > footer {
  grid-area: foot;
  background-color: #8cffa0;
}

grid-template-areasString, associated with grid item’sgrid-area, which defines an area.

grid-template

yesgrid-template-rowsgrid-template-columnsandgrid-template-areasAbbreviation.

Its value can be divided into three situations:

  • none
  • Use only when defining rows and columnsrows/columnsGrammar, such asgrid-template: 100px 1fr / 50px 1fr;
  • When all three are used sometimes, one is also used/It’s separated, and it’s still on the rightcolumns, but its left syntax is<line-names>? <string> <track-size>? <line-names>?
.page {
    grid-template: [header-top] "a a a"     [header-bottom]
                   [main-top]   "b b b" 1fr [main-bottom]
                   / auto 1fr auto;
}
/*
Line names are optional, custom names, which need to be wrapped in brackets. They are actually equivalent to comments
The associated value of the string grid item grid area
Size of the line track size
*/

#page {
  display: grid;
  width: 100%;
  height: 200px;
  grid-template: [header-left] "head head" 30px [header-right]
                 [main-left]   "nav  main" 1fr  [main-right]
                 [footer-left] "nav  foot" 30px [footer-right]
                 / 120px 1fr;
}

header {
  background-color: lime;
  grid-area: head;
}

nav {
  background-color: lightblue;
  grid-area: nav;
}

main {
  background-color: yellow;
  grid-area: main;
}

footer {
  background-color: red;
  grid-column: foot;
}

 

grid-row-gap / row-gap

Used to set the size of the gutter between line elements. Its values can be length, percentage, andnormal

CSS grid layout was initially defined by grid row gap attribute, and now it is gradually replaced by row gap. However, in order to be compatible with browsers that do not support row gap properties, you need to use properties with prefixes.


.box{
    grid-row-gap: 1em;
}

 

grid-column-gap / column-gap

Used to set the size of the gutter between element columns. Its values can be length, percentage, andnormal

normalThe default interval is 1em for multi column layouts and 0 for other types of layouts.

andgrid-row-gapLike, it’s graduallycolumn-gapReplace.


.page {
    grid-column-gap: 1em;
}

 

grid-gap / gap

It is the abbreviation of the above two attributes. The syntax isrow-gap column-gap。 Withoutcolumn-gapThen it will be set to followrow-gapThe same value.

It also graduallygapReplace.


#grid {
  display: grid;
  height: 200px;
  grid-template: repeat(3, 1fr) / repeat(3, 1fr);
  gap: 20px 5px;
}

#grid > div {
  background-color: lime;
}

 

Implicitly created rows and columns

CSS gird automatically adjusts the location of each item on the grid based on the size and span of the surrounding items.

For example:


.box {
  display: grid;
  grid-template: 25px / 100px 160px;
  background: #000;
}
.box * {
  background: #ccc;
}
.box *:nth-child(even) {
  background: #777;
}

We only define one row, two columns. But we have five sub elements. The CSS grid decides to extend them to implicitly created spaces, and the columns in the newly created implicit rows are automatically expanded from the previously specifiedgrid-template-rowsProperty inherits row height.

grid-column-start , grid-column-end , grid-row-startandgrid-row-endThese four properties are on grid item, which can define the location of a grid item. If we set its location beyond the grid we defined, then we will also implicitly create rows or columns.

grid-auto-rows

Specifies the size of the implicitly created row. Its value can be:

  • Length valuepx em vmaxetc.
  • Percentage: relative to grid container
  • flex: non negative, in unitsfrTo define the elasticity coefficient of the grid orbit size. Each definesflexThe remaining free space is allocated proportionally to the
  • max-contentKey, which means that the grid track is occupied by the largest content of grid items
  • min-contentKeyword, indicating that the grid track is occupied by the largest and smallest content of grid items
  • autoIf the grid orbit is the largest, it is equivalent tomax-content, is the minimum, equivalent tomin-content

Its value sumgrid-template-rowsIt’s the same.


.box {
  display: grid;
  grid-template: 25px / 100px 160px;
  gap: 10px 20px;
  grid-auto-rows: 50px;
  background: #000;
}
.box * {
  background: #ccc;
}
.box *:nth-child(even) {
  background: #777;
}

 

grid-auto-columns

Specifies the column width of the implicitly created grid. Its value andgrid-auto-rowsSame.


#grid {
  height: 100px;
  display: grid;
  grid-template-areas: "a a";
  grid-gap: 10px;
  grid-auto-columns: 200px;
}

#grid > div {
  background-color: lime;
}

 

grid-auto-flow

It controls how the automatic layout algorithm works and precisely specifies how the elements in the grid are arranged.

If we were in adivWrite severaldiv, and then set the parentdisplay: grid;From a visual point of view, we can see that there is no change. But if we take the fatherdivadd a sentencegrid-auto-flow: column;We found that now the sub elements are displayed in one line, which is similar to the effect of elastic box.

grid-auto-flowThe values of are as follows:

  • Row specifies that the automatic layout algorithm arranges elements by filling them in row by row, and adds new rows if necessary. (default)
  • Column specifies that the auto layout algorithm arranges elements by filling them in columns, adding new columns if necessary.

After these two keywords, you can also adddenseKeyword. Grammar is[ row | column ] || dense

This keyword specifies that the automatic layout algorithm uses a “dense” stacking algorithm, which attempts to fill the blank left in front of the grid if a smaller element appears after it. Doing so will fill in the blanks left by the larger elements, but it may also cause the original order to be disrupted.

If it is omitted, a “sparse” algorithm is used. When layout elements in the grid, the layout algorithm will only “move forward” and never back to fill in the blank. This ensures that all auto layout elements appear “in order,” even though it may leave a space filled with subsequent elements.

grid-auto-flow: row;

grid-auto-flow: row dense;

 grid

gridIs a CSS shorthand property that includes almost all of the properties mentioned above (exceptgap )。

As with other shorthand properties, if a secondary property is not declared, it uses the initial value. In addition, although the shorthand declaration cannot set the gutter of the grid, the gutter will be reset by the declaration.

Its values can be divided into three categories

grid-template

Just andgrid-templateIn short, such asgrid: [linename1] "a" 100px [linename2];

grid-template-rows / [ auto-flow && dense? ] grid-auto-columns?

grid-template-rowsSet row height(grid-template-columnsSet tonone ), /Hinderauto-flowMust write(grid-auto-flowSet tocolumn) finallygrid-auto-columnsSet how to repeat the train track automatically(grid-auto-rowsAttribute is set toauto )。

asgrid: repeat(3, [line1 line2 line3] 200px) / auto-flow 300px;

[ auto-flow && dense? ] grid-auto-rows? / grid-template-columns

This kind of writing is contrary to the previous one. This is the settinggrid-template-columnsrowsAttribute isnone) Optional settingsgrid-auto-rowsAttribute (columnsbyauto

asgrid: auto-flow dense / 30%;

Properties on grid items

 grid-row-start, grid-row-end, grid-column-start, grid-column-end

Specify the row start bit, row end bit, column start bit and column end bit of grid item in the grid respectively.

It is necessary to understand the concept of grid line introduced before. The horizontal line increases from top to bottom, and the vertical line increases from right, starting from 1.

They can take the following values:

autoIndicates auto placement, auto span, or defaultspanFor 1numberRepresent gridlinesSpan digitIt means crossing several grids,numberLess than or equal to0Invalid. If the grid size is exceeded, rows or columns are implicitly created.

Its sumtableA bit similar

If the set position exceeds the specified size, it will get unstable effect, which should be avoided.


.box {
  display: grid;
  grid: 100px 100px / 100px 100px;
  background: #000;
}
.box * {
  background: #ccc;
}
.box *:nth-child(even) {
  background: #777;
}
.box1 {
  grid-column-start: span 5;
}

 

grid-row, grid-column

grid-rowandgrid-columnThe above 4 properties are abbreviated.

The syntax of their values isstart / end。 If there is only one value then it isstartendValue is default.auto

When the number of columns is unknown, you can use the-1Let it extend all the way to the end of the grid.

Use negative values

 

grid-area

We’ve shown it abovegrid-areaandgrid-template-areasUsage of combination.grid-areaActually, it is.grid-row-startgrid-column-startgrid-row-endandgrid-column-endAbbreviation.

Its default value isgrid-area: auto;

If four values are set, the order is

grid-area: row-start / column-start / row-end / column-end;

If 3 values are set, the last one isauto

If two values are set, the last two areauto

If 1 value is set, then the last three areauto

If the first isCustom representation, all ignored are custom representations

.box1 {
  grid-area: a / a;
}

/*Equivalent to*/

.box1 {
    grid-row-start: a;
    grid-column-start: a;
    grid-row-end: a;
    grid-column-end: a;
}

Content alignment of grid items

We can usealign-selfandjustify-selfAdjust the content alignment of grid items.

align-selfUsed for vertical alignment,justify-selfUsed for horizontal alignment.

align-self

This property can also be used for flex layouts. It usually has three values as follows:

  1. Start: align top of content
  2. Center: content vertically centered
  3. End: align bottom of content

 

justify-self

It usually has three values as follows:

  • start / left: align content left
  • cneter: content horizontal center
  • end / right: align content right

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

[Redis5 source code learning] analysis of the randomkey part of redis command

baiyan Command syntax Command meaning: randomly return a key from the currently selected databaseCommand format: RANDOMKEY Command actual combat: 127.0.0.1:6379> keys * 1) “kkk” 2) “key1” 127.0.0.1:6379> randomkey “key1” 127.0.0.1:6379> randomkey “kkk” Return value: random key; nil if database is empty Source code analysis Main process The processing function corresponding to the keys command is […]