CSS
Raiting:
7

Introduction to CSS3 Grid Layout. Working with grids


Introduction


image
In my opinion CSS3 Grid Layout Module is one of the most interesting modules in the CSS3 family. The official history of the module as a draft specification is a little less than a year. Also, in December, 2010, there was made the preliminary announcement about CSS Grid Alignment at TPAC 2010 written by Vladimir Yunev. It should also be noted that with a slightly different name and slightly different syntax, but with the same essence, it was declared as a WD as early as 2007. Today, the development of the final design of the module is in full swing, and the pre-implementation is already in Internet Explorer 10, and there is a hope that the support of the new features will also appear in future versions of other popular browsers.

Why do we need Grid Layout?


The task that is completed by the CSS3 Grid Layout is very simple and clear to any web coder. It provides a convenient mechanism for the location of content on a virtual grid.

In contrast to the old table-based approaches that use the table, here is not littered semantics of the document and its presentation clearly is separated from the content. Unlike the different variations of the block layout with a complex structure and the wild floats, here a description of styles is trivially simple and clear. Also, it keeps the flexibility. As distinct from today's popular css/js-libraries, here is not littered binding of classes for the grid layout (for example, let’s take a look at bootstrap or yui css grids).

It is a pleasure to work with it! It remains only to wait for the broad support :) However, if you plan on making an application in the Metro style for Windows 8 in html/js, there are already described the key features in CSS3 Grid Layout Module, they are already working and allow using the comfortable and practical mechanisms.

Basics


In order to work quickly with the Grid Layout, let us immediately start with an example. Imagine that you need to work out the classical task of three-column layout with like this content:

<section>
<header>Title</header>
<nav>Menu</nav>
<article>Content</article>
<aside>Notes</aside>
<footer>Footer</footer>
</section>

which should be broken on the three columns like this:
image
This is the classical task, so I will not talk about this. Let's see what can be done using Grid Layout (I'm skipping the browser prefixes in the examples, but in practice they need to be added - for IE this is -ms-).

Here is a sample code for CSS:

section {
display: grid;
grid-columns: 150px 1fr 200px;
grid-rows: 50px 1fr 50px;
}

section header {
grid-column: 2;
grid-row: 1;
}

section nav {
grid-column: 1;
grid-row: 2;
}

section article {
grid-column: 2;
grid-row: 2;
}

section aside {
grid-column: 3;
grid-row: 2;
}

section footer {
grid-column: 2;
grid-row: 3;
}

All you need to do in its simplest form is to ensure that there is specified section in the container. The inner content should be placed along the grid and set the virtual grid, using the properties of grid-columns and grid-rows (I will talk about the values that they accept below). Next, it is enough for each element inside just to specify where it should be placed.
image
That's it! Altogether we have:

The virtual grid: grid-columns and grid-rows in the container
Placement of element: grid-column and grid-row.

Now, let's understand the details and additional possibilities.

Virtual Grid

Tracks: rows and columns


In order to create the virtual network along which the items will be placed further, it is necessary to describe the Grid Tracks – the rows and columns within the grid:

#grid {
display: grid;
grid-columns: 150px 1fr; /* two columns */
grid-rows: 50px 1fr 50px; /* three rows */
}

Grid lines


The tracks are arranged between the Grid Lines, which are on the right to left and on top to bottom from each track:
image
In order to set how the item will be placed along the grid, you must specify a horizontal and vertical line, where it will be bound:

#item {
grid-column: 2;
grid-row: 2;
}
image
By default, the item takes up space from a specified line to the next one (therefore, this numbering coincides with the numbering of cells).

Spanning for a few cells


In order to span the item for a few grid cells, you can use the grid-row-span and the grid-column-span:
#item {
grid-column: 2;
grid-column-span: 3;
grid-row: 2;
grid-row-span:2;
}
image
By default, both properties are set to 1, which corresponds to the spanning of space available from the specified line to the next one (+1).

Repeating tracks


It often happens that the intended grid for use contains a typical pattern:

#grid {
display: grid;
grid-columns: 24px 120px 24px 120px 24px 120px 24px 120px 24px;
grid-rows: 1fr 24px 1fr 24px 1fr 24px;
}
image
It would be convenient to describe such grids in a more compact and clear form – here you go! The above example can be described as follows:

#grid {
display: grid;
grid-columns: 24px (120px 24px)[4];
grid-rows: (1fr 24px)[3];
}

The pattern itself is described in parentheses, followed by the square brackets that indicate the repeating number.

Now that we know the basic features to describe the grid lines, let's get back to the tracks and try to deal with used units of measurement.

Units of measurement


As you may have noticed above, here and there I used an unusual value when specifying the sizes of some columns and rows - 1fr. Now I am going to discuss that below.

When describing the column width and the row height (the size of the tracks), you can use the following units and values:
Linear sizes - standard units of length that are defined in the CSS3 Values and Units Module, for example, pt, px, em, vw, etc.
Percentage - the size of the track as a percentage from the container size with the grid (although if the height or length of the grid depends on the content, the result will be undefined).
Fraction - non-negative number, followed by the unit fr, the size of each fraction is taken proportional to the specified number (see details below).
Max-content - keyword to specify the maximum length from the maximum lengths of items in the track.
Min-content - keyword to specify the maximum length from the minimum lengths of items in the track.
Minmax (min, max) - sets the range of values (the principle of operation can be described as minmax (p, q) = max(p, min(fill-available, q)) – a maximum of the lower level and a minimum of available space and the upper level).
Auto - the keyword, equivalent minmax (min-content, max-content).

Fractions


Let's try to figure out how a fraction value works. The grid takes some space of the width and the height. It may depend on the content, as well it could be rigidly fixed or occupy all available space in the outer container. Next, when describing the tracks, you can explicitly specify the sizes of the rows and the columns, keeping in mind that their length depends on the content.

Now, if we subtract from the available length allocated for the vertical or horizontal grid the sum of all content lengths, the remaining space is distributed among the remaining tracks in proportion to their specified fractions (the size of the fraction is divided by the sum of all such fractions):
image
In the picture above they are three columns with widths in the ratio 2:1:1 and two lines with heights in the ratio 5:2.

Example


In a draft specification is provided a complex example, which allows seeing all of this scheme with different types of values at once:
#grid {
display: grid;
grid-columns: 100px 1fr max-content minmax(min-content, 1fr)
}

Here we define the following lines (the tracks, they are also columns in this case):

1. Starting first line.
2. The line is in 100px from the first.
3. Another line is at a distance of half remaining after all the space calculations from the second line.
4. One more line, which distance from the third line is equal to the maximum of the content size of items in the column.
5. Finally, the last line is located from the fourth at a distance that is equal either a minimum length of items in a column, or half the remaining space, whichever is greater.

There is still a small nuance about the record keeping of fractions, which were inside of the function minmax: they are considered in the total amount of fractions only if indicated in the maximum position. The fractions that are indicated in the minimum position are considered equal to 0px. In order to get more info go to the specification.

The next step is to try to understand how the items are placed between the grid lines (within cells).

Binding items


Now, when the items are bound to the grid lines, the natural question arises: how do they lie between the lines?
image
Binding items to the cell borders is controlled by the properties, such as grid-column-align and the grid-row-align. You can use the following values for controlling:
start
end
center
stretch

I think the actions are obvious from the title, but I note only one thing that the positioning of item is done by its margin-box. The default value is stretch.
image
Binding in the columns (horizontal) corresponds to the direction of the text (for example, in Arabic language start will be on the right and end on the left). Binding in the rows (vertical) coincides with the direction of blocks flow.

Layers controlling


Here is another important point: the location of items within the grid overlay. What happens if, for example, two items are tied to the same lines, or overlaid during the extension in the number of cells?

First of all, it is important to understand the nuance of the following: the items that are placed within the grid do not directly affect the location of each other. If you bound the ten items to the second horizontal and the third vertical lines, then by default they will overlay each other, as if each of them is bound to the corresponding corner. Items can only affect the track sizes if they are tied to the sizes of the content.
image
To control the display order of layers, the current version of the specification extends the z-index, allowing you to control the layers of items within the grid.

Annotation: In previous version of the specification upon which is based the current version of IE10 (platform preview 5), for these purposes have been defined an individual property grid-layer, so it will not interfere with the z-index, however, a working group reviewed the decision in the course of discussions.

Example of use:

grid {
display: grid;
grid-columns: (1fr)[3];
grid-rows: (1fr)[4];
}

#A {
grid-column:1;
grid-row:3;
grid-column-span:2;
}

#B {
grid-column:1;
grid-row:1;
grid-row-span:2;
/* grid-layer: 10; */
z-index:10;
margin-top:10px;
}

#C {
grid-column:1;
grid-row:1;
grid-column-span:2;
margin-left:50px;
}

#D {
grid-column:2;
grid-row:3;
grid-row-span:2;
grid-column-span:2;
margin:10px 0 0 10px;
}

#E {
grid-column:2;
grid-row:2;
/* grid-layer: 5; */
z-index:5;
margin: -20px;
}
image

CSS3 Grid Library


To start working with grids in the browsers that don’t support CSS Grid Layout Module, you can use eCSStender (js-library) and CSS3 Grid Alignment extension, providing support for the following properties:
display: grid
grid-columns & grid-rows
grid-column & grid row
grid-column-span & grid-row-span

An example can be found here.

Let’s talk a bit about future or what other features are described in the module


Finally, let's take a look at the future and see what other features will be included in the CSS3 Grid Layout Module.

Please keep in mind the features that are mentioned below described only in a draft specification and they are not supported by the released browsers (including the preliminary versions). They also may be changed in the future, depending on community feedbacks and the recommendations of CSS working group.

Indication of the final line to bind the item


Optionally, in order to bind the item to the grid, you can indicate not only the start, but the final line.

#item {
grid-column: 2;
grid-row: 2 4;
}
image
In contrast to the span mechanism, which tells how many cells the item must be stretched horizontally or vertically, this feature allows you to explicitly specify the line where the item should end. It is also convenient to use in conjunction with the possibility of naming the individual lines of the grid.

Named grid lines


The lines can be named for convenience. This is done by inserting the string values in the appropriate places when describing the tracks (you can give a few names if it makes practical sense, for example, in terms of semantics of layout):

#grid {
display: grid;
grid-columns: "nav" "first" 150px "content" 1fr "last";
grid-rows: "header" 50px "content" 1fr "footer" 50px;
}

Next, when describing the item binding you can refer to these names:

#menu {
grid-column: "nav";
grid-row: "content";
}

#header {
grid-column: "content";
grid-row: "header";
}

#article {
grid-column: "content";
grid-row: "content";
}
image
Also, the specification introduces four pre-named lines, such as horizontal, vertical, start, and end, framing the entire grid. This allows placing the item from the second column to the last without thinking about the total number of columns.

#menu {
grid-column: 1;
grid-row: start end;
}

#footer {
grid-column: 2 end;
grid-row: 3;
}
image
Named cells and templates

Another way to place the items along the grid is to use the templates, allowing to describe the structure of the virtual blocks:

#grid {
display: grid;
grid-template: "ln"
"ma"
"ba"
"ff";

grid-columns: auto minmax(min-content, 1fr);
grid-rows: auto minmax(min-content, 1fr) auto auto;
}
image
At the same time to place the item with binding to a particular virtual cell is sufficient to refer to it using the appropriate rule:

#article {
grid-cell: "a";
}

This approach is especially convenient if you need to change the layout, and even alter the very grid depending on various conditions, such as screen resolution. In this situation, the best was is when Grid Layout is combined with Media Queries:

@media (orientation: portrait) {
#grid {
display: grid;
grid-template: "ln"
"ma"
"ba"
"ff";

grid-columns: auto minmax(min-content, 1fr);
grid-rows: auto minmax(min-content, 1fr) auto auto;
}
}

@media (orientation: landscape) {
#grid {
display: grid;
grid-template: "ln"
"ma"
"mb"
"sf";

grid-columns: auto minmax(min-content, 1fr);
grid-rows: auto minmax(min-content, 1fr) auto auto;
}
}

#article {
grid-cell: "a";
}
image

Conclusion


I tried to give an overview of key features of CSS3 Grid Layout Module in this article. I hope they inspire you :)

Let me remind you that the module continues to evolve, and the editors gather feedbacks from the external community and within the CSS working group. The current implementation of the basic functional can be viewed in Internet Explorer 10. Several interesting examples can be found at ietestdrive.com: The Grid System and the Hands On: CSS3 Grid Layout:
image
Enjoy this article!
Sparks 25 april 2012, 5:21
Vote for this post
Bring it to the Main Page
 

Comments

Leave a Reply

B
I
U
S
Help
Avaible tags
  • <b>...</b>highlighting important text on the page in bold
  • <i>..</i>highlighting important text on the page in italic
  • <u>...</u>allocated with tag <u> text shownas underlined
  • <s>...</s>allocated with tag <s> text shown as strikethrough
  • <sup>...</sup>, <sub>...</sub>text in the tag <sup> appears as a superscript, <sub> - subscript
  • <blockquote>...</blockquote>For  highlight citation, use the tag <blockquote>
  • <code lang="lang">...</code>highlighting the program code (supported by bash, cpp, cs, css, xml, html, java, javascript, lisp, lua, php, perl, python, ruby, sql, scala, text)
  • <a href="http://...">...</a>link, specify the desired Internet address in the href attribute
  • <img src="http://..." alt="text" />specify the full path of image in the src attribute