Introduction to CSS Grid Layout. CSS Grid and Flexbox: comparison in practice. Grid Placement Properties

From the author: When creating complex websites, grids make a huge difference. Their importance in modern web design becomes clear, you just have to 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 - on commercial sites this technology cannot be used yet.

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 a polyfill, and yes, the 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 varied. IN this section I'll talk about a few terms that you will need to remember when working with grids:

Units of measurement fr: Use these to set the amount of 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 – 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 parent element and one or more children. For example, I'll take the markup below:

A
B
C
D
E
F

< 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 given cell grid, you need to set the positioning of this element via CSS. Before I explain how to move mesh elements, take a look at the image below.

In this example we will use a linear element placement system. 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. In addition to the vertical lines, this element is located between the lines on the first and second row.

To set the starting vertical line 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:

Header
Main Content
Extra Info

< 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 this. 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 property values.

We'll tell you how CSS Grid allows you to create high-quality responsive markup without resorting to third-party frameworks like Bootstrap.

The native grid offers numerous advantages over frameworks, especially when compared to the most popular one: Bootstrap. Because modern CSS allows you to create complex markup without the need for JavaScript, your code is cleaner and easier to maintain.

Markup could be simpler

Replacing Bootstrap with CSS Grid will do HTML is cleaner. As an example, consider a small piece of the page that we have to layout, it looks like this:

Bootstrap

First, let's look at the example code for this page in Bootstrap.

There are a few things to pay attention to:

— Each row should be located in its own div.
- You must use class names to create markup (col-xs-2).
— As the template grows and becomes more complex, the same will happen with the HTML code.

If we talk about responsiveness, the markup will look even worse:

CSS Grid

Now let's look at the same example of markup in pure CSS:

This markup is much easier to read. The clutter of classes is gone and the number of divs has been reduced.

Of course, unlike the example with Bootstrap connected to the page, here you need to describe the styles yourself:

More flexibility

Let's work on adaptability. For example, let's remove MENU from top row For mobile screens. In other words, let's change this:

CSS Grid

Rebuilding the CSS grid is very easy. All you need to do is simply add a media query and describe what should happen to the page elements.

This way, you don't even need to open the HTML to redesign the page.

Bootstrap

If a developer needs to change something in a Bootstrap template, he will have to start by changing the HTML itself. In fact, you need to move the MENU so that it is above the HEADER.

In this case, simply changing the behavior of styles in media query will not work. To solve this you need to resort to JavaScript.

No more 12 column limit

Not that this is a serious limitation, but in some cases it causes inconvenience. Because the Bootstrap grid is basically divided into 12 columns, problems could arise with division, for example, into 5, 7 or 9 columns.

CSS Grid allows you to create as many columns in a row as you need.

This is done by setting the value of the grid-template-columns property:

By the way, it uses flexbox, which also makes it easy to manage markup via CSS, but at the moment it is not even out of beta yet.

Browser support

As of this writing, 75% percent of browsers support CSS Grid.

There is nothing stopping many developers from starting to use CSS Grid right now, but, unfortunately, not all projects are ready to work with this layout method. However, many well-known developers, such as Morten Rand-Eriksen from LinkedIn and Jen Simmons from Mozilla, are convinced that this approach to creating pages is the future: visual representation should be separated from JavaScript logic and adapt independently of it.

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
The price for all this is just a little extra markup. I think these days, when the cost of a person's watch is much more expensive than hardware and productivity, it's not hard to guess which way the scales are tipping.

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; 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

Hi all! Today we will talk about what are grid systems? or simply flexible grids in adaptive layout.

First let's define what it is Grid System.

Grid System- a collection of class-based styles that allow the user to control the page layout using a system of rows and columns.

Let's imagine we have a blog page. It is divided into 2 columns: the main part on the left, and the sidebar on the right. Let's try to create a flexible grid for such a page.

Well, first we have to do something basic, but... html markings






Here we have a block that contains the entire page, it contains a block with a blog, which contains 2 blocks: the main part of the page and the sidebar.

So our entire page will be the size 960px. The entire grid is divided into 12 columns 69px. each. The blog part will be wide 900px. The main part of the page will be 566px, sidebar - 331px.

This is what we get in the end

#page (
margin: 36px auto;
width: 960px;
}

Blog (
margin: 0 auto 53px;
width: 900px;
}

Blog.main (
float: left;
width: 566px;
}

Blog .sidebar (
float: right;
width: 331px;
}

Everything would be fine, but, as you can see, all this is static, specified in pixels. We want our grid to change its size depending on what screen the page is viewed on, therefore, we need to set everything in percent. Let's do this.

For this there is the same formula as for fonts

goal / context = result

Let's convert a block of the entire page from pixels to percentages.

#page (
margin: 36px auto;
width: 90%;
}

90% chosen because in this case we will also have indents along the edges along 5% . However, you can choose a different value.

We use our formula: 900 / 960 = 0.9357

Let's multiply the result by 100 to receive interest, and we will register it in our css.

Blog (
margin: 0 auto 53px;
width: 93.75%;
}

The same thing needs to be done with the columns, but notice that the context has changed. Because the columns are inside a block with a class .blog, then it will be the context. Let's do the math.

566 ÷ 900 = .628888889

331 ÷ 900 = .367777778

We convert everything into percentages and write it in the style sheet.

Blog.main (
float: left;
width: 62.8888889%;
}

Blog .sidebar (
float: right;
width: 36.7777778%;
}

That's all! Now we have a flexible grid and can use it for layout.

As you can see, everything is very simple. At the core flexible mesh, like a flexible font, there is still the same formula, remembering which, you can easily create responsive websites.

The note! As you can see, we ended up with quite long percentage values. Some may advise you to round them up, but you should never do this! Remember!

And that’s all for me, thank you for your attention and successful adaptive layout!

Especially for site users, we provide a practical lesson on using the 960 Grid system. Imagine that we were given a design for layout. First, we must outline a plan for implementing the site structure, and only then proceed directly to the code. After studying this article, you will be able to handle any classic layout in the shortest possible time and natural hair color for many years (without gray hair). So here's our design:

1. Create a mesh

As you already know, the 960 Grid system uses a whole range of classes and is available in several variants (12 column and 16 column versions). The main container, regardless of the number of columns, will always be 960px wide. For this design we will choose a 12 column system. Each block in the 960 Grid system has margin(margin) 0 10px. This guarantees us even, proportional padding of 20px. For those who are confused by the 960px size, I advise you to take a look at this diagram. This size is optimal for the vast majority of monitor resolutions. So, we have the ability to create blocks of this width:

  • 140px
  • 220px
  • 300px
  • 380px
  • 460px
  • 540px
  • 620px
  • 700px
  • 780px
  • 860px
  • 940px

Each size has its own class, the name of which is based on the grid_X scheme, where X is the number of columns. If you need a 960px block, then you should select the grid_12 class. In order to activate the 960 Grid system, you must parent container set the class container_12 or container 16. Below is small example page consisting of 3 blocks. The width of the first one is equal to the width of 960px, the remaining 2 are half as large:

Remember that when you fill a row with blocks with the grid_X class, make sure that in total they add up to no more than 12. For example, like we have - two blocks grid_6 + grid_6 = 12. Less is possible: 6, 4, 2, etc. d. Now that we've gone over the basic principles, we can begin the practical exercise:

2. Create a Mock-Up

Let's try to build a diagram of what we need to make up. First of all, we need 2 blocks of 960px. One for the logo, the other for navigation. Next are 2 blocks (on one line), for a poster and website presentation, a separator block (full width), 4 columns (on one line), again a separator block and a footer. Something like this:

I think after seeing the image you already know what classes we need. Try them out yourself, and then take a look at the code below to see if you're thinking correctly:

Remember that at the end of each line we need to insert

for normal display in all browsers. Don't forget to also include 960 Grid CSS on your page in the head section.

So, the skeleton is ready, so it's time to start decorating. Set the height and background color block separators. The height of the menu block will depend on the menu itself. Also don't forget to add your logo:

Div.spacer ( background-color: #8FC73E; height: 1em; ) div#navbar ( background-color: #8FC73E; padding: 10px 0; )

This is what we should get:

We are not interested in information at all right now, so you can insert content from here into the central columns this page. Before you get started top part, let's take care of the bottom one. In our design, the footer background is colored grey colour. At the moment we cannot implement this because if you remember, there is some indentation between the blocks that will not allow us to completely paint over this area. To solve this problem, let’s move 3 blocks related to the footer into separate blocks with id = footer. One more detail: when we use classes within classes, it would be good to set the alpha values ​​(in order to indicate which block will be the first and omega - for the last):

Div#footer ( background-color: #e5e5e6; )

Perfect! Our footer now has a background color. Add some text to it and let’s move on to the navigation block. According to all laws modern principles layout, navigation is an unnumbered list. Add the following code and style:

  • Articles
  • Topics
  • About
  • Editors
  • Contact

Div#navbar ul ( list-style: none; display: block; margin: 0 10px; ) div#navbar ul li ( float: left; margin: 0 1.5em; font: bold 1em Arial; )

Cool! Everything is going well for us. All that remains is a block with a poster and a presentation of the site, but before we start implementing them, I would like to say a few words about CSS frameworks in general.

3. CSS frameworks will not solve all your problems

Before you start laying out your design using a CSS framework, you should take into account some of the disadvantages of these systems. Reading this article you couldn't help but notice that the page construction rules are very strict. Everything has its own fixed size. When you change the width of one block, you have to change others. In any case, something must be sacrificed. For example, what will you do if you have a 1000px design, and 960 Grid allows you to create a maximum width of 960px... And you want 1000px! Without a massive code change, this is impossible to implement. For example, the client wanted a wider site or the designer disagrees with your implementation. There is another problem regarding the height of the speakers. If three columns have the same background color (like our footer), it is necessary that these columns be same height. Another significant disadvantage: the use of additional indents and the creation of frames leads to the destruction of the entire layout. In order to add what is necessary and not destroy anything, you need to compensate for the added dimensions. Now I'll show you how. Let's start finishing the top part.

4. Upper section

First, let's solve the problem with the column height - make it fixed. Next, let's create empty divs in one and the other block. They will contain a drawing or text information. Padding We won’t install it because you can upset the proportion of the grid width. Let's create a small outer indent for the p tags so that the text looks nice.

IN in this case for style it is better to create a class rather than an ID, because we need to apply it to several blocks. If necessary, this will also allow us to change the height in 2 counts. This is what our classes look like:

Div.topSection div ( border: solid 10px #e5e5e6; height: 280px; ) div.topSection div p ( margin: 10px; )

Cool! Let's see what we got:

Ready to fill out? Then add some text to the left block, but don’t overdo it so as not to exceed the height. In fact, in real projects, the designer must calculate all this (the number of characters that will satisfy the block size); Before you insert an image into the right block, you need to decide on its dimensions, if you have not already done so. This can be done early in the design or through FireBug. Click Inspect. Click on the div we need. Select the Layout tab. After this you will see all the information you need. The following image will help you:

In the screenshot, the poster measures 360x280. Find an image and style it:

Img#poster ( width: 360px; height: 280px; )

That's all! The template is ready. Now all that remains is to fill it with real content and post it online:

5. Know your options

Now that everything is ready, let's summarize. 960 Grid allowed us to rivet a template in 15 minutes. Cool? Yes! Have we tested it in IE6, IE7? No! Must? No. This is just the beginning! So what's now? Now you need to show it to the customer and see the reaction. If he is satisfied with this, then we can start testing, but if not, and the customer wants something more complicated, then he will have to write everything from scratch himself. I'll repeat it again. CSS frameworks do not solve all problems. Despite this, thousands of developers use them as a regular web development tool because, like any tool, CSS frameworks have their own field for wide application. In any case, if the design requests are not super specific (80% of cases), then using 960 Grid you can save a lot of time - and time is money!