CSS Grid and Flexbox: comparison in practice. Layout on Grid in CSS. Complete guide and reference. Flexbox solution
Danny Markov
The design is quite simple - it consists of a center-aligned container, inside of which we have a header, a main section, side panel and a basement. Here are the main "tests" we should run while keeping the CSS and HTML as clean as possible:
- Place four main sections of the layout.
- Make the page responsive (the sidebar falls below the main content on small screens).
- Align header content - left navigation, right button.
As you can see, for the sake of comparison, we kept everything as simple as possible. Let's start with the first test.
Test 1: Laying out page sections
Flexbox solution
Add display: flex to the container and set the direction child elements vertically. This positions all the sections underneath each other.
Container ( display: flex; flex-direction: column; )
Now we need to make sure that the main section and the sidebar are located next to each other. Since flex containers are usually unidirectional, we need to add additional element.
We then set this element's display: flex and flex-direction to the opposite direction.
Main-and-sidebar-wrapper ( display: flex; flex-direction: row; )
The last step is to set the dimensions of the main section and sidebar. We want the main content to be three times as wide as the sidebar, which is easy to do with flex or percentages.
As you can see, Flexbox did everything well, but we also needed quite a lot of CSS properties plus an additional HTML element. Let's see how CSS Grid will work.
CSS Grid solution
There are several options for using CSS Grid, but we will use the grid-template-areas syntax as the most suitable for our purposes.
First we'll define four grid-areas, one for each section of the page:
Now we can set up our mesh and define the location of each area. The code may seem quite complicated at first, but once you become familiar with the grid system, it becomes easier to understand.
Container ( display: grid; /* Define the size and number of columns of our grid. The fr unit works like Flexbox: the columns divide up the available space in the row according to their values. We will have two columns - the first is three times the size of the second. */ grid-template -columns: 3fr 1fr; /* Link the previously made areas to places in the grid. The first line is the header. The second line is divided between the main section and the sidebar */ grid-template-areas: "header header" main sidebar" "footer footer"; /* The spacing between grid cells will be 60 pixels */ grid-gap: 60px; )
That's all! Our layout will now follow the above structure and we've set it up so that we don't have to deal with margin or padding.
Test 2. Making the page responsive
Flexbox solution
This step is strictly related to the previous one. For a Flexbox solution, we will have to change the flex-direction and adjust the margin.
@media (max-width: 600px) ( .main-and-sidebar-wrapper ( flex-direction: column; ) .main ( margin-right: 0; margin-bottom: 60px; ) )
Our page is fairly simple, so there's not a lot of work in the media query, but a more complex layout would require a lot of rework.
CSS Grid solution
Since we've already defined grid-areas , we just need to redefine their order in the media query. We can use the same speaker setup.
@media (max-width: 600px) ( .container ( /* Align grid areas for mobile layout */ grid-template-areas: "header header" "main main" "sidebar sidebar" "footer footer"; ) )
Or we can redefine the entire layout from scratch if we think this solution is cleaner.
@media (max-width: 600px) ( .container ( /* Convert the grid to a single-column layout */ grid-template-columns: 1fr; grid-template-areas: "header" "main" "sidebar" "footer"; ) )
Test 3: Aligning Header Components
Flexbox solution
We have already done a similar layout with Flexbox in one of our old articles -. The technique is quite simple:
Header ( display: flex; justify-content: space-between; )
The navigation list and button are now aligned correctly. All that remains is to place the items inside
Header nav ( display: flex; align-items: baseline; )
Only two lines! Not bad at all. Let's see how CSS Grid handles this.
CSS Grid solution
To separate the navigation and button, we must add display: grid to the header and set up a two-column grid. We will also need two additional lines in CSS to position everything within the appropriate boundaries.
Header( display: grid; grid-template-columns: 1fr 1fr; ) header nav ( justify-self: start; ) header button ( justify-self: end; )
Regarding single line links within navigation, we were unable to do this correctly with CSS Grid. Here's what our best attempt looks like:
Header nav ( display: grid; grid-template-columns: auto 1fr 1fr; align-items: end; )
It's clear that CSS Grid didn't handle this part of the layout well, but that's not surprising - the focus is on the alignment of the containers, not the content inside them. This system is not for putting finishing touches.
conclusions
If you read the entire article (and it's a great job!), the conclusions should not surprise you. Actually no better system- both Flexbox and CSS Grid are good in their own way and should be used together, and not as an alternative to each other.
For those of you who jumped directly to the conclusions of this article (don't worry, we do that too), here's summary comparisons:
- CSS Grid is great for creating a big picture. This system makes it easier to manage page layout and can even deal with irregular and asymmetrical designs.
- Flexbox is great for aligning content within elements. Use this system to place small design details.
- Use CSS Grid for 2D layouts (rows AND columns).
- Flexbox works better in only one dimension (rows OR columns).
- There is no reason to use only CSS Grid or only Flexbox. Study them and use them together.
In this article you will find full course by 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 new approach to create adaptive 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 full video to learn CSS grids to get the hang of it in no time 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 ⇣
Once upon a time I wrote about an unusual service, which is an AI for creating a website. Judging by the current results, they turned out “so-so”, especially considering the stated price. in this regard they will be more effective.
Today I want to talk about a “technology” that is similar in name, but completely different in essence - CSS Grid! The post consists of several parts:
This approach to building layouts makes it easy to create enough flexible meshes sites from using CSS. In the future it will probably be used everywhere. If I understand correctly, it is perfect for the same tasks as Flexbox, but unlike it, it can simultaneously work in two-dimensional dimensions (columns and rows). Below I offer a translation of the article, which is a kind of introduction to the topic and contains simple educational examples. Attention! The author of the note is conducting a free(!) course on CSS Grid in December, if you want, send a request to his Email.
I also found a useful video on the topic on the Internet. Perhaps it is easier for someone to perceive information like this:
Introduction to CSS Grid
This year, this technology received built-in support in Chrome, FF, Safari, so it is likely that it will become a popular tool in the near future. But for now, you need to remember to take care of outdated and lagging web browsers.
The simplest mesh
There are 2 main objects here:
- parent / wrapper (wrapping all the internal blocks that make it up);
- children/items (the elements themselves).
Here is the simplest design:
Wrapper ( display: grid; )
However, immediately after this, nothing much will change, since the display format is not defined. You will see 6 DIVs following each other.
Columns and Rows
To make your grid two-dimensional you need to specify the parameters of the rows and columns - use the options grid-template-row And grid-template-colum respectively:
.wrapper ( display : grid; grid-template-columns : 100px 100px 100px ; grid-template-rows : 50px 50px ; ) |
Wrapper ( display: grid; grid-template-columns: 100px 100px 100px; grid-template-rows: 50px 50px; )
Since there are three values for the columns, the same number of them will be generated, therefore, there are only 2 rows. The numbers in pixels set the width of the elements in the first case (100px each), and the height (50px) in the second.
Here's another example to help you better understand how it works:
.wrapper ( display : grid; grid-template-columns : 200px 50px 100px ; grid-template-rows : 100px 30px ; ) |
Wrapper ( display: grid; grid-template-columns: 200px 50px 100px; grid-template-rows: 100px 30px; )
The following image will be displayed:
Location and dimensions
With this feature you will get really very powerful capabilities for creating site grids. Let's say we have a size of 3x3:
.wrapper ( display : grid; grid-template-columns : 100px 100px 100px ; grid-template-rows : 100px 100px 100px ; ) |
Wrapper ( display: grid; grid-template-columns: 100px 100px 100px; grid-template-rows: 100px 100px 100px; )
If the HTML code, as in our example, has 6 DIV elements (see at the very beginning), then in in this case Only 2 rows will be displayed on the site, the third will temporarily not be filled. However, when we start using different parameters for position and block sizes - grid-columnand grid-row, the situation will change.
We assign styles to one of the objects:
.item1 ( grid-column-start : 1 ; grid-column-end : 4 ; ) |
Item1 ( grid-column-start: 1; grid-column-end: 4; )
This means that the DIV with the class item1 starts from the first line of the column in the grid and ends on the 4th, that is, it fills the entire row.
Actually, now some objects have moved to last line, which we had written down in advance (3x3). There is a simpler option:
.item1 ( grid-column : 1 / 4 ; ) |
Item1 ( grid-column: 1 / 4; )
.item1 ( grid-column-start : 1 ; grid-column-end : 3 ; ) .item3 ( grid-row-start : 2 ; grid-row-end : 4 ; ) .item4 ( grid-column-start : 2 ; grid-column-end : 4 ; |
Item1 ( grid-column-start: 1; grid-column-end: 3; ) .item3 ( grid-row-start: 2; grid-row-end: 4; ) .item4 ( grid-column-start: 2; grid-column-end: 4)
It gives us the following picture:
Did you manage to figure it out? In principle, it’s not difficult, but you need to understand that this is only the basic part of the nuances of CSS Grid.
Prototyping and Layout Areas with CSS Grid
The markup code is as follows (HTML):
Container ( display: grid; grid-template-columns: repeat(12, 1fr); grid-template-rows: 50px 350px 50px; grid-gap: 5px; )
If everything is clear in principle about the rows, then the columns need to be clarified. Here in the meaning grid-template-columns a grid is created that consists of 12 identical columns(width of each = 1/12 of the total) + padding between them of 5px (grid-gap).
Add grid-template-areas
The option gives even more flexibility and amazing features. Perhaps the syntax and formatting of the parameter grid-template-areas looks a little unusual, but further you will understand why everything is exactly like this:
.container ( display : grid; grid-gap: 5px ; grid-template-columns : repeat (12 , 1fr) ; grid-template-rows : 50px 350px 50px ; grid-template-areas : "h h h h h h h h h h h h" "m m c c c c c c c c c c c" "f f f f f f f f f f f f " ; ) |
Container ( display: grid; grid-gap: 5px; grid-template-columns: repeat(12, 1fr); grid-template-rows: 50px 350px 50px; grid-template-areas: "h h h h h h h h h h h h" "m m c c c c c c c c c c c" "f f f f f f f f f f f f f" ; )
It's kind of visual representation your site grid in CSS. All characters in this parameter form 3 rows and 12 columns, defined by the line above. Each letter corresponds to one cell. The names in the example correspond to the blocks of HTML code: header (h), menu (m), content (c) and footer (f), but you can use any other options.
Assigning Areas Templates and Experiments
On next step you "logically link" container characters and DIV elements:
.header ( grid-area : h; ) .menu ( grid-area : m; ) .content ( grid-area : c; ) .footer ( grid-area : f; ) |
Header ( grid-area: h; ) .menu ( grid-area: m; ) .content ( grid-area: c; ) .footer ( grid-area: f; )
The site will display a layout like this:
And now the magic begins. Let's swap some letters in the parameter grid-template-areas, for example, “c” and “m” in places:
grid-template-areas : "h h h h h h h h h h h h h" "c c c c c c c c c c c m m" "f f f f f f f f f f f f" ; |
grid-template-areas: "h h h h h h h h h h h h h" "c c c c c c c c c c c m m" "f f f f f f f f f f f f";
The grid will look different:
Adding adaptability to this design generally looks amazing. You couldn't do this with HTML alone, but in CSS everything is possible: ". h h h h h h h h h h ." "c c c c c c c c c m m" ". f f f f f f f f f f ." ;
grid-template-areas: ". h h h h h h h h h h ." "c c c c c c c c c m m" ". f f f f f f f f f f .";
The website looks like this:
No scripts or HTML - just the magic of CSS Grid!
Additional Grid and Flex Examples
Later on CSS Tricks I found another article on the topic, some options from it may be useful to you. Follow the links to (logo in the code block on the top right) to see the example in action on the big screen.
Classic site layout
We have a header and footer stretched to the full width, and between them there is a content block with two sidebars. In the first case, when the screen is reduced, all objects will remain in the same positions as before.
If you need the blocks to be located one below the other, then:
2 column blog grid
Let's say in our center big block content and sidebar. The code below keeps all objects in place when the page size is reduced.
The second technique is to arrange them one after the other.
Width distribution of elements
Visually, the example resembles a gallery, when all the pictures are next to each other in several columns. As you decrease the size, fewer and fewer of them will appear on each line.
Picture inside the article
Here the content is divided into 2 parts, and between them there is a full-screen block.
Total. In general, I discovered the concept of CSS Grid, which, to be honest, pleasantly impressed me - especially the frames where layout areas with different letters were considered. Of course, these are all just the basics of the “technology”, plus I did not describe in detail each parameter of the code. The examples in the last section of the article are more complex and should be reviewed carefully. It combines both Flex and Grid. If this topic is interesting, subscribe to the courses of the first author - Email entries in the original first or second note.
Do you have anything to add regarding CSS Grid? — write thoughts, advice or send interesting links.
I think you already know that Grid is superior to Flexbox for creating layouts. But what about responsive layouts? Which is better to use Flexbox or Grid? Both can work with responsive layouts. You might think Flexbox is a better fit, after all - Flex items can stretch, shrink, change direction, etc. But Grid actually has some new tricks that will save you a lot of time and trouble for responsive layouts.
Minmax function
The first one is brilliant new tool Grid, a minmax function that allows us to define ranges for the columns and rows in our layout. In this example, we have an orange sidebar, and we want the width to be at least 100 pixels, but no more than 30% of the container's width. The width of the container is 500 pixels, so our sidebar happily takes up 30% (150 pixels).
Here is the exact same code, but the container width is less than 150px. Now ours minimum value fires and ensures that the orange sidebar is not smaller than 100 pixels.
The way the minmax function works is amazing, in most cases you won't even need to use media queries.
We can achieve a similar effect using Flexbox, but it takes a bit more work and code. We must use a combination of flex-grow, min-width, max-width:
The Grid method is more flexible and easier to adapt. The code is almost two times less.
One rule for all elements
If you do need media queries, with the Grid layout it's easy to do. Let's say we want to change this layout to mobile device in one column. With Flexbox, we will need to change every element in the layout to override the minimum width. There is no need to override the maximum width, since the minimum width takes precedence.
If you have a simple layout, this approach works quite well. But the more complex your layout, the more elements will need to be overridden through media queries. With the help of Grid, this problem is much easier to solve.
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: “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 weak side. 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 and for working with the Grid. And using their example, you can very quickly master basic principles 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; for this we will 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