CSS Grid and Flexbox: comparison in practice. Create a nested grid
From the author: When creating complex websites, grids make a huge difference. Their importance in modern web design becomes clear once you look at the number of frameworks in which this technology has been implemented to speed up development.
Once you are familiar with the CSS Grid Layout specification, you will no longer need separate files styles if you want to work with a grid system. An equally important benefit is that you will no longer rely on inline and float properties to position elements on the page. In this tutorial we will learn the basics of grid systems and also create a simple blog layout.
Browser support
On this moment Only IE 10+ and Edge support the Grid Layout specification; this technology cannot yet be used on commercial sites.
IN Chrome this The option can be activated via the “Experimental Web Platform features” flag in chrome://flags. In Firefox – layout.css.grid.enabled flag.
Another option is to use polyfill, and yes, polyfill CSS Grid Polyfill exists! You can use any of the three options described and study Grid Layout while it is still at an early stage of development.
Please note: In IE it currently works old version specification, which means the browser does not fully support the new specification. When we get to the examples, I recommend you use Chrome or Firefox.
Grid System Terminology
As for the positioning of elements, CSS Grid systems are the same tables. However this tool much more powerful and diverse. In this section, I will talk about a few terms that you will need to remember when working with grids:
Units of measurement fr: they are used to set the size free space. Used in conjunction with grid-rows and grid-columns. From the specification: “Space allocation occurs only after all “lengths” or sizes of rows and columns of content have been reached maximum sizes»
Lines: Lines mark the boundaries of other elements. They are both horizontal and vertical. In the picture below there are 4 vertical and 4 horizontal lines.
Tracks: Tracks are the space between parallel lines. In the picture below there are 3 vertical and 3 horizontal tracks.
Cells: Cells are the building blocks of a grid. There are only 9 cells in the picture below.
Areas: An area is a rectangle of an arbitrary number of cells. Those. a track is both an area and a cell.
Positioning elements in a grid
Let's start with the basics. In this section, I'll show you how to use a grid to place elements in specific places. To work with CSS Grid Layout, you need to create a parent element and one or more children. For example, I'll take the markup below:
< div class = "grid-container" > < div class = "grid-element item-a" >A< / div > < div class = "grid-element item-b" >B< / div > < div class = "grid-element item-c" >C< / div > < div class = "grid-element item-d" >D< / div > < div class = "grid-element item-e" >E< / div > < div class = "grid-element item-f" >F< / div > < / div > |
To create a grid, the container must specify the properties display:grid or display:inline-grid, as well as other styles:
Grid-container ( display: grid; grid-template-columns: 200px 10px 0.3fr 10px 0.7fr; grid-template-rows: auto 20px auto; )
Grid - container ( display:grid; grid - template - columns : 200px 10px 0.3fr 10px 0.7fr ; grid - template - rows : auto 20px auto ; |
The grid-template-columns and grid-template-rows properties set the width of the rows and columns. In the example above I created 5 columns. A 10px wide column is used as a separator between elements. The first column has a width of 200px. The third column takes up 0.3 of the remaining space. And the fifth column takes up 0.7 of the remaining space.
Since the first row is set to grid-template-rows: auto, this allows the row to expand as content is added. The 20px line works as a separator. In the demo below you can see that the elements are pressed tightly against each other.
Pay attention to element B - it is located in the second column, which we use as a separator. If the positioning of elements is not set manually, the browser will place elements in cells from left to right, and if they do not fit in one row, then the remaining ones will jump to the second row. That's why we left 4 spare columns on the second line.
To move an element to a given grid cell, you need to set the positioning of this element via CSS. Before I explain how to move mesh elements, take a look at the picture below.
In this example we will use a linear element placement system. A linear system means that the lines in the grid will play a dominant role in the placement of elements. Let's take element B as an example. Horizontally, this block starts on the third line and ends on the 4th line of columns. Except vertical lines this element located between the lines on the first and second row.
In order to set the starting vertical line of an element, we will use the grid-column-start property. In our case, the value will be 3. The grid-column-end property indicates the ending vertical line of the element. In our case it is 4. Values for horizontal lines are displayed in the same way.
Based on the above, we conclude that to move element B to the second cell, you must use the code:
Element-b ( grid-column-start: 3; grid-column-end: 4; grid-row-start: 1; grid-row-end: 2; )
Element - b ( grid - column - start : 3 ; grid - column - end : 4 ; grid - row - start : 1 ; grid - row - end : 2 ; |
Similarly, to move element F to the sixth cell:
Element-f ( grid-column-start: 5; grid-column-end: 6; grid-row-start: 3; grid-row-end: 4; )
Element - f ( grid - column - start : 5 ; grid - column - end : 6 ; grid - row - start : 3 ; grid - row - end : 4 ; |
Creating a Basic Layout
Now we will create a basic blog layout, which will have a header, footer, sidebar and two sections for content. First the markings:
< div class = "grid-container" > < div class = "grid-element header" >Header< / div > < div class = "grid-element sidebar" >Sidebar< / div > < div class = "grid-element main" >Main Content< / div > < div class = "grid-element extra" >Extra Info< / div > < div class = "grid-element footer" >Footer< / div > < / div > |
Remember that the order in which tags are placed in the markup does not affect the positioning of elements on the web page. Without changing the CSS, you can put the footer in the markup above the header, but the positioning of the elements will still remain the same. But I don't recommend doing that. The main idea here is that the markup no longer tells you where the element will be located.
All we have to do is define the values of properties like grid-row-end for all elements. As in the previous example, we will use a grid diagram to determine the property values.
In this article you will find a complete course on CSS grids. We will look at what it is, what are the differences with FlexBox and how you can work with CSS Grid.
CSS grids are a new approach to creating responsive websites with many blocks located anywhere on the site. Besides CSS Grid There is also a technology that is very similar to meshes. We will not go into the smallest differences between them, since this would require a separate article, but we will briefly describe the main differences.
CSS Grid can be called a cooler and improved version FlexBox, because FlexBox allows you to work only in one plane: either create columns or create rows.
CSS grids allow you to do more because they work on both planes at the same time. Thus, creating adaptive website blocks is much easier, and the possibilities for arranging objects as you please are simply endless.
We invite you to watch a full video on learning CSS grids to instantly understand the essence CSS Grid:
- Lesson on ;
During the lesson, three pages were created, the code for each page can be copied below.
First file
Second file
Third file
Principle of operation
Working with grids is very simple. The algorithm of actions here is as follows:
- We create one main block and place other blocks in it ( sections);
- Add the display: grid property to the main block;
- CSS grid properties can now be applied to all main block elements;
- Adding various properties. You can find documentation on all possible properties;
Each block can be set in width, height, and location. Blocks that are created based on grids immediately have adaptive design, which adapts blocks to different screen resolutions.
This way you can write less and get more. What else could be cooler? Share your experience of using grids in your projects in the comments to this article ⇣
I noticed the Grids technique about a year ago. Then this technique, after a very superficial study, seemed useless and very experimental to me; I was repulsed by the fact that for implementations it was necessary to create extra markup. But now it is becoming difficult not to notice the number of websites built on the grid, as well as the number of articles and tutorials about it. Thanks to the latter, it has become much easier to study and understand the principles and concepts, to make more or less real conclusions. My conclusion a year later is: “It’s simple and useful solution which was ever created for the layout of web pages, every self-respecting web designer should know.”
Anyone who has ever worked with a grid knows what a grid is. graphic editors (Photoshop, Fireworks, Gimp, etc.) and of course appreciated its necessity when creating any design. But how to implement a Grid on the web? In fact Tabular the layout was a real web page design with a Grid, undoubtedly very convenient. But not the intended use of elements table was horrifying.
Fortunately, the enormous popularity of web standards has grown and continues to grow over last years, as well as their support in modern browsers, gave us the opportunity to create multi-functional pages with very little, logical markup. This layout was called Block. But also Block layout turned out to be a weak point. When creating pages with a huge set of elements of different sizes and meanings, marking up such pages has become a very difficult task, and if more than one person works on the markup, such work can become a nightmare.
And then the technique using the Grid came to the rescue. This technique is a hybrid between Block And Tabular layout. Using it gives us:
- speed and ease of development
- freedom of positioning
- proportionality of page elements and their placement
What is layout with Grid? First of all, it's a concept. A concept that includes many design aspects and very few rules for its implementation. This gives complete freedom and no standardization in its execution. I will say even more - the same Grid can be implemented by the most different ways. If you have already read about the Grid, you may have noticed that each author starts from a new angle, going deep into the details, this is, to put it mildly, confusing. Luckily they started to appear Grid Systems- CSS libraries for working with the Grid. And using their example, you can very quickly master the basic principles of this technique.
I think it makes no sense to write about all aspects of the Grid; you can easily find information about it on the Internet. I suggest creating your own simple Grid System.
First you need to understand that the grid consists of columns and spaces between them. There are three main values - the grid width, the column width, and the width of the space between the columns. The width of the columns depends on their number.
Let's try to make a grid 950 pixels wide with 16 columns with 10 pixel spacing, so one column should be 50 pixels wide. Having understood all the values, we open any graphic editor known to us and create a layout. You can also add padding to the Grid on the left and right, say 20 pixels each, and this will result in a layout with a width of 990 pixels. You can see my example.
Now we can start creating our library. Like most CSS libraries ours needs a global reset, I suggest Eric Mayer's CSS Reset, keeping reset.css let's create grid.css to which we can immediately add a method for cleaning containers containing floating blocks - Clear Fix. The first thing we need is a rule for a container that will contain all our columns. The width of each container is equal to the width of our grid.
.container(
margin: 0 auto;
width: 950px;
}
Now we can add a rule for our columns, it contains the width and padding. The indent acts as a gap (gutter) between the columns.
.column(
float: left;
margin-right: 10px;
overflow: hidden;
width: 50px;
}
The last column does not need an indentation; to do this, let’s add a rule for it as well:
Our containers contain columns, the columns are floating blocks, so they have to be cleaned. To avoid unnecessary .clearfix in the markup, you can apply this rule to containers:
.clearfix:after, .container:after{
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}clearfix, .container( display: inline-block; )
/* Hides from IE-mac \*/
*html.clearfix, *html.container(height: 1%;)
.clearfix, .container(display: block;)
/* End hide from IE-mac */
Now we can start with our columns. Columns can be two or three wide, and so on. To do this, we can apply the following rules to them:
.span-1 ( width: 50px; )
.span-2 (width: 110px; )
.span-3 (width: 170px; )
.span-4 (width: 230px; )
.span-5 (width: 290px; )
.span-6 (width: 350px; )
.span-7 (width: 410px; )
.span-8 (width: 470px; )
.span-9 (width: 530px; )
.span-10 (width: 590px; )
.span-11 (width: 650px; )
.span-12 (width: 710px; )
.span-13 (width: 770px; )
.span-14 (width: 830px; )
.span-15 (width: 890px; )
.span-16 ( width: 950px; margin-right: 0; )
In principle, this is all that is needed for Grid implementations; you can also add a wrapper and a class for viewing the Grid with a layout. Let's create main.css and add to it:
.wrapper(
margin: 0 auto;
width: 990px;
}
.overlay(
background: transparent url(overlay.png) repeat-y scroll top left;
}
Here's what the layout might look like:
I think this is enough for a start.
You can see my example
I noticed the Grids technique about a year ago. Then this technique, after a very superficial study, seemed useless and very experimental to me; I was repulsed by the fact that for implementations it was necessary to create extra markup. But now it is becoming difficult not to notice the number of websites built on the grid, as well as the number of articles and tutorials about it. Thanks to the latter, it has become much easier to study and understand the principles and concepts, and draw more or less real conclusions. My conclusion a year later is this: “Every self-respecting web designer should know this simple and useful solution that has ever been created for the layout of web pages.”
Anyone who has ever worked with graphic editors knows what a grid is. (Photoshop, Fireworks, Gimp, etc.) and of course appreciated its necessity when creating any design. But how to implement a Grid on the web? In fact Tabular the layout was a real web page design with a Grid, undoubtedly very convenient. But not the intended use of elements table was horrifying.
Fortunately, the enormous popularity of web standards, which has grown and continues to grow in recent years, as well as their support in modern browsers, has given us the opportunity to create richly functional pages with very little, logical markup. This layout was called Block. But also Block layout turned out to be a weak point. When creating pages with a huge set of elements of different sizes and meanings, marking up such pages has become a very difficult task, and if more than one person works on the markup, such work can become a nightmare.
And then the technique using the Grid came to the rescue. This technique is a hybrid between Block And Tabular layout. Using it gives us:
- speed and ease of development
- freedom of positioning
- proportionality of page elements and their placement
What is layout with Grid? First of all, it's a concept. A concept that includes many design aspects and very few rules for its implementation. This gives complete freedom and no standardization in its execution. I will say even more - the same Grid can be implemented in a variety of different ways. If you have already read about the Grid, you may have noticed that each author starts from a new angle, going deep into the details, this is, to put it mildly, confusing. Luckily they started to appear Grid Systems- CSS libraries for working with the Grid. And using their example, you can very quickly master the basic principles of this technique.
I think it makes no sense to write about all aspects of the Grid; you can easily find information about it on the Internet. I suggest creating your own simple Grid System.
First you need to understand that the grid consists of columns and spaces between them. There are three main values - the grid width, the column width, and the width of the space between the columns. The width of the columns depends on their number.
Let's try to make a grid 950 pixels wide with 16 columns with 10 pixel spacing, so one column should be 50 pixels wide. Having understood all the values, we open any graphic editor known to us and create a layout. You can also add padding to the Grid on the left and right, say 20 pixels each, and this will result in a layout with a width of 990 pixels. You can see my example.
Now we can start creating our library. Like most CSS libraries ours needs a global reset, I suggest Eric Mayer's CSS Reset, keeping reset.css let's create grid.css to which we can immediately add a method for cleaning containers containing floating blocks - Clear Fix. The first thing we need is a rule for a container that will contain all our columns. The width of each container is equal to the width of our grid.
.container(
margin: 0 auto;
width: 950px;
}
Now we can add a rule for our columns, it contains the width and padding. The indent acts as a gap (gutter) between the columns.
.column(
float: left;
margin-right: 10px;
overflow: hidden;
width: 50px;
}
The last column does not need an indentation; to do this, let’s add a rule for it as well:
Our containers contain columns, the columns are floating blocks, so they have to be cleaned. To avoid unnecessary .clearfix in the markup, you can apply this rule to containers:
.clearfix:after, .container:after{
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}clearfix, .container( display: inline-block; )
/* Hides from IE-mac \*/
*html.clearfix, *html.container(height: 1%;)
.clearfix, .container(display: block;)
/* End hide from IE-mac */
Now we can start with our columns. Columns can be two or three wide, and so on. To do this, we can apply the following rules to them:
.span-1 ( width: 50px; )
.span-2 (width: 110px; )
.span-3 (width: 170px; )
.span-4 (width: 230px; )
.span-5 (width: 290px; )
.span-6 (width: 350px; )
.span-7 (width: 410px; )
.span-8 (width: 470px; )
.span-9 (width: 530px; )
.span-10 (width: 590px; )
.span-11 (width: 650px; )
.span-12 (width: 710px; )
.span-13 (width: 770px; )
.span-14 (width: 830px; )
.span-15 (width: 890px; )
.span-16 ( width: 950px; margin-right: 0; )
In principle, this is all that is needed for Grid implementations; you can also add a wrapper and a class for viewing the Grid with a layout. Let's create main.css and add to it:
.wrapper(
margin: 0 auto;
width: 990px;
}
.overlay(
background: transparent url(overlay.png) repeat-y scroll top left;
}
Here's what the layout might look like:
I think this is enough for a start.
You can see my example
Around 2012 or 2013, I was introduced to web development. Gradually I began to study this direction on my own. I soon realized that CSS makes a lot of things meaningful, but it doesn't create adequate markup. There are so many hacks that it is too difficult to understand them. That is why in modern standards, which will be discussed in this article, special attention was paid to working with markup.
What you will learn from this article:
- how you used to work with CSS markup;
- difference between legacy approaches and modern standards;
- how to get started with new standards (Flexbox and Grid);
- why should you care about these modern standards.
How we used to work with CSS markup
Task
Let's model a fairly standard problem: how to create a page with two sections - a sidebar and a main content area - that are the same height, regardless of the size of the content?
Here's an example of what we're aiming for:
Side panel and an area with main content of the same height, regardless of the size of the content
First, I'll show you how to solve this problem using legacy approaches.
1. Create a div with two elements
For example,
Obviously main has more text.
Let's highlight aside with a color to make it easier to distinguish:
Aside ( color: #fff; background-color: #8cacea; )
2. Place both sections side by side
To do this, we will write the following:
Aside, main( float: left; )
This style divides the available space in the required proportions and sets aside and main to float.
Two blocks located next to each other
For those unfamiliar with float: it's relative old way moving elements left or right.
As you can see in the image above, the task is still not completed - the height of the sidebar does not match the height of the main area. Let's fix this.
3. Use the display: table trick
To solve this problem, you need to use display: table .
If you're not familiar with it, here's what to do:
- We make the parent container (in our case the body element) a table: body ( display: table; )
- We remove the float and make the child elements aside and main table cells: aside, main( display: table-cell; )
Once we have done this, the problem can be considered solved. By at least, this is how it was solved before.
Both blocks are now the same height.
Difference between legacy approaches and modern standards
Now that you have an idea of how the problem has been solved in the past, let's take a look at what Flexbox and Grid can do.
Flexbox and Grid are the ideal solutions for CSS markup and are modern standards. If you need to write CSS code at a good level, then be sure to study them.
Solving a problem using Flexbox
The Flexbox formatting context is initialized by creating a flex container.
The parent element is body . It contains a sidebar and a main area. Create a container:
Body ( display: flex; )
Flexbox in action
Let's not forget about proportions:
Aside (width: 25%; ) main (width: 75%; )
Problem solved
You can do many different things with Flexbox:
And I've only touched on the tip of the Flexbox iceberg.
Flexbox is available in most supported browsers. It can be fully used in Firefox from version 28, Chrome from 29, Safari from 6.1 and Edge from 12.
Note translation Ours will help you understand Flexbox.
Solving the problem using Grid
Unlike Flexbox, which mostly works in one dimension, with CSS Grid you can use both rows and columns. Let's see how to solve our problem with its help.
It all starts the same way as in the case of Flexbox. Create a container:
Body ( display: grid; )
Here's all the CSS:
Body ( display: grid; background-color: #eeeeee; ) aside ( color: #fff; background-color: #8cacea; )
And this is what we get:
Primary option
Grid is available in most supported browsers, although in smaller quantities. It can be fully used in Firefox from version 52, Chrome from 57, Safari from 10.1 and Edge from 16.
Our latest image is still no different from the previous ones. So what is the magic?
What if we split the width proportions like before:
Aside (width: 25%; ) main (width: 75%; )
Proportional width distribution for child elements
Yes, the result is different, but it does not suit us. The sidebar is not yet located to the side of the main area.
Here we come to the essence of Grid markup. After initializing the Grid container with display: grid, you need to define the rows and rows within it.
Here's how it's done:
Body ( grid-template-columns: 30% 70%; )
A one-line solution is beautiful, isn't it? grid-template-columns defines the proportions of the columns in the grid.
Problem solved
Nose using Grid much more can be done.
First, let's add a little color to the main block to make the examples more clear:
Main ( background-color: rgba(39,174,96,1); color: #fff; )
This is what we should get:
Filling the main content area with color
Let's see what good Grid has to offer:
- You can define a gap between columns: body ( grid-column-gap: 15px; )
Here's the result:
It looks much neater with a gap between the columns.
There is no need to add padding to the aside and main blocks: grid-column-gap does that.
- You can make as many columns as you need. The examples above used only one element aside and main . Let's add two more:
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Added a line break
To simplify things, you can use the shortcut: grid-gap: 15 px instead of grid-row-gap and grid-column-gap .
- You can define row sizes: body ( grid-template-rows: 200px 300px 400px; )
Different row heights
Now the height of the first, second and third lines is 200, 300 and 400 pixels respectively.
This is enough for a start - but this is not all.
How to get started with the new standards?
You've seen an example of how Flexbox and Grid provide more convenient solutions for marking. So how to start?
Why should you care about these standards?
If you still don't understand why Flexbox and Grid are worth using, here are a few problems you may encounter with the previous solutions:
- if you use floating blocks and clearfix, you know that they can cause problems;
- at absolute positioning elements can overlap each other;
- using display: table leaves a lot of unnecessary markup;
- When using inline-block there will be problems with empty spaces.