CSS Grid - Swiss Army Knife for Website and Application Layouts

Original author: JavaScript Teacher
  • Transfer
Over the past two months I have gone deep into learning CSS Grid. In this post I want to share my main points. To make it clearer, I will explain everything with diagrams.

You are probably already familiar with the block CSS model for regular elements. Let's start with a similar “general overview” for the CSS Grid: At the core of the CSS Grid structure is the main container, which is plain , having , and . To create a CSS grid container, add a property . The mesh elements are descendants placed inside the parent container. They are usually defined as a list describing the , , or other similar elements of the site layout, depending on its design.


divmarginborderpaddingdisplay: gridheadersidebarfooter

In this case, we have 3 div. The third is stretched to 2 cells.

Note that the lines can be counted in the opposite direction, using a negative coordinate system.

The grid from the example above is 5 by 4 cells. This is defined as follows:

div#grid {               /* This is our CSS grid parent container */display: grid;
  grid-template-columns: 100px100px100px100px100px; /* 5 cols */grid-template-rows:    100px100px100px100px;       /* 4 rows */
}

The number of rows and columns is determined according to the set values. Lines and extra padding are located between the cells. The rows and columns between the lines are called grid bars. The number of lines will always be equal to [number of cells + 1] in a given direction. So 5 columns will have 6 lines, while 4 lines will have 5 lines. In the following example, we see 7 columns and only 1 row:


One of the first features that can be noted in the CSS grid behavior (by default, the CSS grid does not have a border, so lines 1 from top to bottom and 1 from left to right begin in the upper left corner of the first element, the indent is not applied to them, the grid line is placed in the middle of the indent; even if the property is set padding, the indent is not applied to the first and last lines)

First, it should be noted regarding the CSS grid that the external lines do not depend on the size of the interval. Internal lines only. We will take a closer look at this later when we look at the fractional units ( fr ).

The CSS grid is two dimensional. Elements can be placed horizontally (column) or vertically (row). Set the property value grid-auto-flow.

This works the same way as Flex:


Use grid-auto-flow: rowor grid-auto-flow: columnto determine the direction of filling the mesh with elements.

Imagine an abstract grid:



So, we have a general idea of ​​how it works.

The creative part begins when you are faced with the problem of juggling element placement to create a responsive layout. CSS Grid offers several features to achieve this. We will look at them in the next section of this note.

Let's consolidate the knowledge gained by looking at a few examples:



I used only two elements div. And such a grid turned out.

Implicit and explicit content placement


But what happens if we add another item to the list?



Adding item 3 to the same layout will automatically expand it (blue item). This new space is created automatically by copying the values ​​from the first row. Let's add element 4?



Again, the CSS grid decided to stretch element 4 to the remaining space in the second line. This happened because it grid-template-rowsprecisely defines the space for only 1 line. The rest is automatic.

The placement of the blue elements was not indicated by you explicitly. This is an implicit (automatic) placement. The elements just fall into this space.

Explicit content placement


This is what you would expect from cells if you set values ​​for all list items:



Basically, you can control the size in all consecutive rows by adding more values ​​using the property grid-template-rows. Notice, in this case, the elements are no longer hidden. You identified them exactly (25px 75px).

Auto Spacing


CSS Grid offers several properties to automatically stretch cells by variable / unknown value. Here are the main examples of automatic extensions for columns and rows: The



lower example demonstrates the use of the auto keyword. This means that the cell will stretch to fill the entire space remaining in the parent container after it is filled with explicit elements.

CSS Grid Indents


Speaking of CSS Grid, it is impossible to ignore the indents. Indenting is the space horizontally and vertically between the grid cells.

Intervals are controlled using properties grid-column-gapand grid-row-gap:



You can use different indents for both directions. This can be useful for creating video or image galleries:



Indents for different directions (between columns and rows) may differ. But the size of the interval is indicated once for the entire grid in a given direction. As you can see, indents of different sizes for one direction are not allowed:



I would like to be able to set different sizes of indents. I think it would be convenient. Some suggest using blank bands to achieve a similar effect.

Fr units (fractional part)


Fractional parts ( fr ) are unique to the CSS Grid. The fractional part allocates space depending on the remaining elements in the parent container:



Behavior changes, but 1fr remains unchanged, regardless of the use of other values. The fractional part works like percentage values, but is easier and more intuitive when dividing space: The


behavior of changing fractional units is based on all values ​​presented for this direction.

In this example, only the behavior for the columns is shown for clarity. But it works the same way for strings. Just use the property grid-template-row.

Fractional parts and their interaction with indents


The space defined by fractional parts is changed based on indents. The same value of 1fr inside the same parent container will be reduced to a smaller size when the intervals are added:


We add intervals between cells specified using units fr

As we can see, this gives us a pretty good set of tools for placing the content at intervals almost as you like, and without worrying about the values ​​in pixels.

These new changes leave pixel-by-pixel design in the past. Now we think about design using an intuitive approach.

Finally, it gives interesting ideas about using non-integer fr- look at the funny mesh I created. You can define a grid using also numbers with a comma:



Content placement


We just looked at the structure of the CSS Grid. I hope you got an idea of ​​how the content in CSS Grid is structured. Now we have to show imagination and place some elements inside the grid. After that, the standard CSS grid behavior may change. How this happens, we now consider.

To order elements within cells or grid layout areas, you must refer to them along the lines between the cells. No table-like intervals.

CSS Grid allows you to use spacing to determine the width and height of the content area (in cell space), just as it does in a table. We will touch it. But you can and probably should indicate the starting cell using the row number or its name (more on this later). It depends on your preference.

Regarding the placement of content on several cells, the most obvious and attractive is the union of cells.

Merging cell contents


You can combine elements in multiple cells.
Important : the union changes the location of the surrounding elements.

Merge using grid-column and grid-row


Using the properties grid-columnand grid-rowto the following element:



Blue elements changed location after a few cells were combined to accommodate the element 7. The orange elements were pushed to the next row.

There is another way to do the same.

Merging with grid-column-start ...


... grid-column-end, grid-row-startand grid-row-end- you can define specific starting and ending points for which you want to merge cells.

I deleted the elements after 15 (orange) because they are no longer needed:


Set these properties directly for the element to which they should be applied.

Stretching the contents of columns and rows works in both directions.

min-content and max-content


Values min-contentand max-contentare used in properties grid-template-columnsor grid-template-rows, like any other value associated with size (for example, px , 1fr , etc.).



Let's look at this sample. This is our starting point. We change the situation a bit to see how the min / max values ​​affect the cells.

Let's see what results will be obtained if we change one of the columns with the help of min-contentand max-content:



With the text from one word there is no difference between the results obtained, whether we use min-contentor max-content. Hello is the only word. Its minimum and maximum value is the same.

But everything becomes more interesting for more complex text. The following example demonstrates the key idea for min-contenteither max-content:



Here min-content, the longest word in the sentence (stranger) was used as the base width. If used max-content, the entire text string with spaces fills the cell space. But what happens if we apply min-contentor max-contentto all cells?



I noticed that by default the text was centered when I used min-content, although text-align: centerit was not installed.

Images and max-content


I put an image of a blue rose in a cell. And, as expected, the grid expanded to allocate enough space for the image:



When I set the image width exactly 50%, just to see the result, the CSS Grid still retains the cell width 100% of the image size, but displays it with 50% wide (as expected) and automatically centers it horizontally inside the cell.

Both text and image (or other content) will automatically be centered in the CSS Grid cells by default.

Content positioning


Up to this point we have talked in general about the structure of the CSS Grid. Next, we consider how to achieve "multidirectional" displacement within the cell. Of course, we will not use the property float.

Offset in different directions


I do not think that the specificity of CSS Grid calls us to this. However, it is possible to set the offset within 360 °.

It works the same with lowercase and block elements! I think this is my favorite feature from the entire set of CSS Grid.



All 9 combinations are possible using properties align-selfand justify-self. I will explain them below.

align-self


This property helps to position the content vertically.



Use align-self: startto align the contents at the top edge of the cell.
Use align-self: centerfor vertical centering.
Use align-self: endto align with the bottom edge of the cell.

justify-self


This property helps to position the content horizontally.



Use justify-self: startto align the content on the left edge of the cell.
Use justify-self: centerfor horizontal centering.
Use justify-self: endto right-align the cells.

You can use any of the 9 combinations justify-selfand align-selfto align everything in any direction.

Area templates


Area templates are defined using the property grid-template-areas.



Note that the area templates for each line are enclosed in double quotes. Each column is separated by a space. In this example, I just explained how to name the windows. To truly take advantage of the benefits of region patterns, you need to group rectangular blocks of cells with the same name. Tetris blocks are not allowed. You can only use rectangles:



Here Left is an area that combines 3 cells. CSS Grid automatically views it as a single unit. The same with Right. In this simple example, I created 2 columns. But you get the idea. Merge larger areas by giving them names.

To place an element in this area, simply use the property grid-area: TemplateName. In this case,grid-area: Leftor grid-area: Right.

No spaces can be used in the template name. Here I used a dash.

A practical example of using the template areas in the CSS Grid


Now we know how to combine rectangular areas. Let's look at a potential scenario. I will demonstrate a very simple layout.

I created a primitive website layout that has two sidebars, a header and a footer. The main area is in the center and covers an area of ​​3 x 2 cells:



Here we have only 5 elements. Add more and they will be pushed out of the main region into the implicit cells.

Just make sure your windows are always square or rectangular.

Line names


Instead of always referring to the lines by their number, you can name them. Thus, it is easier to remember them for stretching elements in several cells. Numbers can be so tiring!

Below is what this looks like:



Use square brackets to name lines. Then use these names to determine the length that your elements should be stretched with a straight forward slash.

Finally


CSS Grid is a comprehensive, complex subject.

Of course, here is presented a far from complete tutorial on how to create layouts using CSS Grid. I used only one example for each part as a starting point for studying the grid.

I hope the information presented here was useful and inspired to create websites using CSS Grid.

CSS Grid is not only part of HTML. This is a whole system for creating responsive websites and applications.

Its properties and values ​​are based on technologies based on more than a decade of experience creating websites using ordinary HTML tags.


LOOKING.HOUSE - on the project collected more than 150 points looking glass in 40 countries. You can quickly execute the host, ping, traceroute, and mtr commands.



Also popular now: