CSS Grid Layout. Fast start

  • Tutorial
CSS Grid Layout for Image Gallery

Introduction


Hello. February-March 2017 was remembered by many who work with HTML and CSS because most browsers released updates, among which there were updates for CSS. Now you can use the CSS Grid Layout specification without flags in the following browsers: Firefox 52 , Chrome 57 , Opera 44 , Safari 10.1 . Which browser is left behind, I think you can guess. More precisely, it supports the old version of the specification . But the developers of this browser are doing their bestto introduce a new specification. Implementing support for the new CSS Grid Layout specification is the most significant event in the past five years. This specification will completely change the approach to developing user interfaces. And this is awesome.

I am using Flexible Box Layout


Many people ask: “Stop, I use flexbox, why do I need any other grids?”. The question is more than appropriate. CSS Grid will not replace Flexbox and vice versa. The first difference is that Flexbox only works in one dimension. It follows that we can only place flex items along the main axis or along the transverse axis. We cannot place flex items on multiple axes at once. CSS Grid, in turn, allows us to work with markup in two-dimensional space and align content in both dimensions. I love how Tab Atkins explains the difference .

One of the biggest problems in developing user interfaces is that when you change the design, functionality, or behavior of any block, you have to change its layout (in most cases). CSS Grid allows you to change the location of grid elements without changing the HTML itself. Below is an example of simple markup on Flexbox and CSS Grid.


Key Terms

Grid Layout Concepts and Terminology
Before you start working with CSS Grid, you need to understand the basic terms. Based on these terms, the entire specification is built.

A grid container is a set of intersecting horizontal and vertical grid lines that divide the container grid space into grid areas into which grid elements can be placed. Inside the grid container there are two sets of grid lines: one defines the axis of the columns, the other defines the axis of the rows.

Grid lines- These are the horizontal and vertical grid container dividers. These lines are on either side of a column or row. The author can specify a name or numerical index for this element, which he can use further in styles. Numbering starts with one. An important nuance, this element is susceptible to the writing mode that is used on your resource. For example, if you use Arabic or any other language whose writing mode is from right to left, line numbers will start on the right side.

A grid track is the space between two adjacent grid lines, vertical or horizontal.

Grid cell- this is the smallest indivisible unit of grid container that can be referenced when positioning grid elements. Formed at the intersection of the grid row and grid column.

Grid area is the space inside the grid container in which one or more grid elements can be placed. This element may consist of one or more grid cells.

Each element is closely related to each other and is responsible for a specific part of the grid container.

First CSS Grid Layout


We figured out the basic terms. It's time to do our first grid layout. Nothing complicated, a simple layout of three lines in three columns to deal with the basics. Below you can see an example.


В первом варианте из примера мы создаем три колонки размером 150px 1fr 150px и три строки размером 50px auto 50px соответственно. Обратите внимание на такие значения: 1fr, auto. Давайте разберемся, что это за значения.

1fr — это специальная единица измерения введенная в данной спецификации. Она не измеряется в каких-то конкретных единицах измерения (px, em, rem, др.) Из этого следует, что мы не можем использовать ее вместе с функцией calc(). Эта единица измерения не может быть меньше единицы, а также не может принимать отрицательные значения. Она рассчитывается после того, как все остальные значения, отличные от fr, были рассчитаны.

auto- It behaves quite interestingly and uses a tricky algorithm to calculate dimensions. In some situations, this unit may seem to work just as well fr. But this is not so. The main difference autowill be calculated before it is calculated fr. This must be remembered. You can see this behavior from the second and third variants of the example above.

The following rules are used to mark up columns and rows:

grid-template-columns: 150px 1fr auto;
grid-template-rows: 50px auto 50px;

The abbreviated form is as follows

grid-template: 50px auto 50px / 150px 1fr auto;

Typical grid pattern


Let's make a simple template that we are all familiar with. Nothing complicated, the pattern will consist of the following tags: header, nav, aside, article, footer. The vast majority of Internet resources use this template. Just know, even in such a simple template the following problem is observed: “I am a designer, I want it that way. I’m a developer, I can’t do that. ” With the advent of CSS Grid Layout, such a problem should tend to zero.


In this example, we are introduced to a few more CSS Grid Layout properties. The first one grid-template-areas. It is used to create named container grid regions that are not associated with any particular grid element. The syntax is very convenient, we immediately see which template will be output. The second property grid-area. It is used for the grid child of the container. Indicates which named area to place the grid element in.

Let's look at the first option grid-template-areas:

grid-template-areas: "header header"
                     "nav  main"
                     "footer ."

One or more consecutive characters .(periods) have special meanings. If this symbol is used, the browser will render it as a zero token, which in turn means the following: in its place the named area of ​​the container grid will not be created and the grid element cannot be placed in it.

If we did not specify a property for some child grid element grid-area, the browser will automatically distribute such elements. This behavior can be seen from the last option, the above example.

useful links


  1. CSS Grid Layout Module Level 1
  2. How to create a simple layout with CSS Grid Layouts
  3. Grid by Example by Rachel Andrew
  4. A selection of resources for learning CSS Grid Layout by Jen Simmons
  5. Resource for learning CSS Grid Layout by Mozilla
  6. Jen Simmons CSS Grid CSS Grid Layout
  7. My CSS Grid Layout Resource Kit
  8. Many suitable articles (both my own and translations) on CSS Grid Layout on css-live.ru

Instead of a conclusion


In this article, we looked at just the tip of the CSS Grid Layout iceberg. I started to pay attention to CSS Grid Layout when all browsers supported it behind flags. This text is not able to convey my impressions of working with this specification. Sometimes it's hard to believe what kind of things you can do using CSS Grid. This is the gap of all patterns. And I like it.

I advise you to pay attention to this specification and spend a little of your time studying it. Believe me, in the future this will definitely come in handy for you and it doesn’t matter if you write in React, Angular, Vue (insert your own). Grids have come for a long time.

Finally, I will add an example with the arbitrary appearance of a grid element in different named areas.


That's all. Thanks for attention. Who read to the end, special thanks.

Only registered users can participate in the survey. Please come in.

Was this article helpful?

  • 88.7% Yes 165
  • 11.2% No 21

Want to read a more detailed version of the article about CSS Grid Layout?

  • 97.1% Yes 203
  • 2.8% No 6

Also popular now: