How to Create a Responsive CSS Grid Layout. Assigning Areas Templates and Experiments


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 fairly flexible website grids with 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 function you will get really very powerful features on creating site networks. 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 applying different parameters for the position and sizes of the blocks − 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 the last line, which we had written 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 (the width of each = 1/12 of the total) + 5px margins between them (grid-gap).

Add grid-template-areas

This option gives you 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" ; )

This is sort of a visual representation of your site grid in CSS. All characters in this parameter form 3 lines and 12 columns, defined by string higher. 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

In the next step, you "logically link" the container symbols and the 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 we have a large block of content and a sidebar in the center. 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 didn’t describe each code parameter in detail. IN last section Example articles 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.

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

CSS Grid
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima animi, tempore. Vitae consectetur voluptate inventore soluta totam iste dicta neque nesciunt a! Incidunt aliquid quae eveniet blanditiis, laudantium assumenda natus doloribus, fuga mollitia debitis dolorem, soluta asperiores accusamus. Qui, necessitatibus autem doloremque corporis eligendi dolorum natus, eius aperiam consequatur aliquid, quaerat excepturi sequi repellendus, tempora cum sed velit. A voluptates laboriosam quibusdam consequatur quas harum unde sint minus, molestiae quo?
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit, nostrum animi, aliquid consequuntur iusto esse nulla accusamus commodi perferendis deserunt ipsa quidem, illo quam minima aspernatur vero natus?

Second file

CSS Grid
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Lorem ipsum.
Lorem ipsum.
Lorem ipsum.
Lorem ipsum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus magni atque nostrum deleniti magnam unde ad, expedita perferendis laborum aut, pariatur delectus. Deleniti dolores consequuntur sed iure ratione, laudantium exercitationem perferendis reprehenderit delectus aperiam fugiat rerum earum quidem facere aspernatur ipsam harum. Minus alias sequi inventore aspernatur expedita, odio nemo corporis consectetur labore, voluptas quasi.
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Third file

CSS Grid
Box 1
Box 2
Box 3
Box 4
Box 5
Box 6

Principle of operation

Working with grids is very simple. The algorithm of actions here is as follows:

  1. We create one main block and place other blocks in it ( sections);
  2. Add the display: grid property to the main block;
  3. CSS grid properties can now be applied to all main block elements;
  4. 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

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 for as soon as possible 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 an external margin of 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 need to set the parent container to the class container_12 or container 16. Below is a small example of a 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. Let's set the height and background color of the separator blocks. 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 we do the top part, let's do the bottom. In our design, the footer background is colored grey colour. On this 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 the laws of modern layout principles, 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. While reading this article, you couldn’t help but notice that the rules for building a page 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 the 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. We will not set internal paddings 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 this case, it is better to create a class for the style 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!

This article shows how this comparative new technology, it works, and not just a description of properties with superficial examples.

The article itself is a responsive augmented translation of CSS Grid Tutorial

The CSS Grid module was developed by the CSS Working Group to provide the best way to create templates in CSS. It was included in the Candidate Recommendation in February 2017, and major browsers began supporting it in March 2017.

CSS Grid will soon become an integral part of any front-end developer's toolkit. And if you're one of them, then you'll have to learn CSS Grid — which will almost certainly be a non-negotiable skill for any front-end development position.

With this powerful functionality and intuitive syntax, grid templates will undoubtedly change the way the web is built.

Introduction

CSS Grid is new model template, optimized for two-dimensional templates. This is an ideal model for website templates, forms, galleries and anything that requires precise and responsive positioning.

With the development of the web in last years, developing website templates has become increasingly difficult. In the early days of the web, HTML tables were often used for multi-column templates, forms, etc. But this method has its drawbacks. This means that the presentation had to be done at the markup level, so there was no distinction between the presentation and the content. In fact, tables were created to contain tabular data, not to create templates. And without touching on semantic issues, table templates are not created for responsive design.

Floats eventually replaced table templates as the universally accepted and recommended method for creating templates, as it allows us to position elements independently of the layout. However, while this method was considered a significant improvement over tabular layout, it also had its limitations. Floats were primarily designed for document templates and were not suitable for the complex application templates that are now common on the web. Floating elements are difficult to control, especially on devices and viewports different sizes. This led to various grid-like hacks that became the norm, most of them requiring additional markup that detracted from the whole concept of separating content. So the CSS Working Group was looking for a better solution.

The CSS Grid model addresses these issues and more. It allows you to create advanced templates in a fraction of the time you would spend on them with fleets and with less coding.

But of course one could use different meanings, such as 100px , 7em , 30% and so on. You can also assign names to strings along with their sizes.

grid-template-columns: 1fr 1fr 1fr

Same as above, only defines columns in grids.

Exposes a gap. That is, spaces between grid elements. Here we use a vw unit of length, which is relative to the width of the viewport, but we can also use 10px, 1em, etc. The grid-gap property is shorthand for the grid-row-gap and grid-column-gap properties.

Well, the other part of the code simply assigns different styles to the grid elements.

#grid >

repeat() function

You can use the repeat() function to make repeated declarations of an element's size value. For example, instead of doing this:

Grid-template-rows: 1fr 1fr 1fr 1fr 1fr;

We can do this:

Grid-template-rows: repeat(5, 1fr);

Which will significantly reduce the amount of code you need to write, especially if you are working with large and repeating grids.

Creating a Website Template with CSS Grid

Grids include an intuitive "ASCII graphics" syntax in which you can virtually "see" the template in the code, making it very easy to create and modify your template. Even significant changes can be made in a few seconds. This intuitive syntax also helps with responsive web design. Creating different templates for different devices becomes quite a breeze when using grids.

Let's now create a website template that looks like this:

And here is the code for this template:

Example

Header
Article
Ads
Footer

Let's take a closer look at our code. The HTML markup looks like this:

Header
Article
Ads
Footer

And so we will do grid container, so all other elements become grid elements.

Now let's look at the ASCII graphics we talked about before.

Grid-template-areas: “header header header” “nav article ads” “footer footer footer”;

This piece defines our template. Just looking at the code, we can see that it is a 3x3 grid (three rows and three columns). This gives us five grid areas on nine grid cells, since some grid areas span multiple cells.

We also see that the header occupies the entire first row of three cells, and the footer occupies the entire bottom row, also taking up three cells. The navigation, content and advertising sections all share space in the second row, where each of these elements gets one cell.

Now we can assign each of these grid areas to each element:

#pageHeader ( grid-area: header; ) #pageFooter ( grid-area: footer; ) #mainArticle ( grid-area: article; ) #mainNav ( grid-area: nav; ) #siteAds ( grid-area: ads; )

The grid-area property is a shorthand property that allows you to place grid elements on a grid. In our case, we simply refer to the names that we previously specified in grid-template-areas.

Most of the template is already completed. The rest of the code will simply deal with dimensions, spaces and heights, generally more of a decorative area.

The following code gives the sizes of rows and columns:

Grid-template-rows: 60px 1fr 60px; grid-template-columns: 20% 1fr 15%;

The first and third lines are both 60px high, and the second line takes up all the remaining space.

The first column is 20% and the third is 15%. The second one takes all the remaining space.

Changing the template

You can change the template simply by rearranging the grid areas in grid-template-areas .

So if we change to this:

Grid-template-areas: “nav header header” “nav article ads” “nav footer ads”;

As a result, we get the following template:

However, you may need to adjust the dimensions if you move a smaller grid to a larger location.

For example, to do this:

The navigation now takes up the space where the content was, hence the dimensions have been adjusted. Otherwise, we would have narrow content and wide navigation. So the code now looks like this.

Grid-template-areas: “header header header” “article nav ads” /* Before this there was “nav article ads” */ “footer footer footer”; grid-template-rows: 60px 1fr 60px; grid-template-columns: 1fr 20% 15%; /* Before this it was ‘20% 1fr 15%’ */

Creating an adaptive Grid

The grid template has values ​​such as auto-fill and auto-fit that allow you to create a grid with many tracks of a certain size that will fit into a container. This could mean that the grid is responsive, meaning that elements change position as you resize the browser window.

Example of using Auto-fill:

Example

1
2
3
4
5
6
7
8
9

Here's the result:

The code responsible for this:

Grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));

In it, columns are given a minimum size of 150px and a maximum of the remaining space. Such tracks will be repeated as many times as necessary to fit into the container.

The Repeat() function repeats the track definition the number of times specified by the first parameter. Using auto-fill will cause the tracks to repeat as many times as possible until they fill the container.

The size of these tracks is specified in the second parameter. In our case, we use minmax(150px, 1fr) to indicate that the minimum column size is 150px and the maximum is 1fr.

Auto-fit

auto-fit works much the same as auto-fill. The only difference here is that auto-fit pulls together all empty tracks at the end of the placement, while auto-fill does not. The best way here is a demonstration with comparison.

Example

1
2
1
2

Using two small grid elements here will help show the whole concept of work. Auto-fill leaves empty tracks at the end at the specified dimensions, and auto-fit stretches the empty track, which results in tracks being filled with stretched elements to fill the space.

Grids with media queries

One of the strengths of grids is that you can create a completely different template in seconds.

This makes grids ideal for media queries. We can simply reassign the values ​​in ASCII graphics and wrap the result in a media query.

Example

Header
Article
Ads
Footer

This is a three column template on a large viewport and it compresses to a single column on small devices. So this example will look different depending on the screen size. In any case, here is the relevant code for a three-column template for wide viewports.

Grid-template-areas: “header header header” “nav article ads” “footer footer footer”;

And here is the corresponding code for the mobile version:

Grid-template-areas: “header” “article” “ads” “nav” “footer”;

So the whole point is to reassign the values ​​in the grid-template-areas property.

In our case, we wrapped the mobile version in a media query, like this:

@media all and (max-width: 575px) ( body ( grid-template-areas: “header” “article” “ads” “nav” “footer”; grid-template-rows: 80px 1fr 70px 1fr 70px; grid- template-columns: 1fr; ) )

Please note that we have also adjusted the values ​​in grid-template-rows and grid-template-columns to match the new template. In particular, there should be only one column and it should take up all the free space. And since all grid elements will be in one heap, we will assign 5 rows and determine their heights.

Combining grid with block

Depending on your template's requirements, there's nothing stopping you from changing the mobile version to display: block . As here:

@media all and (max-width: 575px) ( body ( display: block; ) )

This will work the same as in the example above, but by default, the elements will appear in their original order. In the example above, the mobile version has a nav below ads, but if we used display: block then the nav would be above ads.

Also using this method, you may also need to add some padding to compensate for the lack of gaps that were included in the grid version.

Explicit and Implicit Grids

CSS Grid uses the concept of explicit grid and implicit grid. This is a key concept that you need to be careful of when creating grids, otherwise you'll end up with a bunch of rows and columns that you never expected were there.

An explicit grid is a grid that you define in grid-template-rows, grid-template-colums, and grid-template-areas.

However, you may still have elements that don't fit into your "explicitly" defined grid. For example, you've defined a grid that can only hold six elements, but the container itself is actually made up of nine elements. Only six elements will fit into the explicit grid and three will remain. And that's where implicit grids come in.

Implicit grids are automatically generated by the grid container whenever grid elements are located outside the explicit grid. The container generates implicit grid tracks by adding implicit rows to the grid. These lines, together with explicit grids, form the implicit ones. Here's an example:

Example

1
2
3
4
5
6

In this example, we explicitly define two rows and two columns, which will accommodate four grid elements. However, there are six grid elements, so an implicit grid was created in order to accommodate the two additional elements.

And that's a very good thing. If the implicit grid had not been created, then the two additional elements would have created a complete mess in the grid.

Setting the track size for implicit grids

You may have noticed that the extra row is not as tall as the previous two. This is because we set the row height in the grid-template-rows property, but it only applies to explicit grids. Row height on implicit grids must be set using the grid-auto-rows property. But since we didn't do this, it turns out that the implicit row uses the auto track size, which is based on the content. This is how the properties for setting the track size are located:

In general it goes like this:

Explicit grid uses grid-template-rows and grid-template-columns

Implicit grid uses grid-auto-rows and grid-auto-columns

Example

In this case, we don't necessarily need to specify the end values ​​on the first element because it only spans one track. The same can be said about the second grid element. By default, if you do not specify an end line, the element will span only one track.

In fact, we didn't need to specify any positioning for the first grid element, since it is at a certain position, it would have been there anyway. But if we had not specified the positioning for the second element, then it would have been located immediately after the first element, occupying only 1 track.

Naming grid lines

You can also name grid lines to make them easier to refer to. This can be done by setting the grid-template-rows and grid-template-columns properties, for example like here:

#grid ( display: grid; /* Set the tracks and name the lines */ grid-template-rows: 50px 1fr 80px ; grid-template-columns: 120px 1fr 80px ; grid-gap: 5px; height: 90vh; ) ... /* Now refer to those named lines */ #item2 ( grid-row-start: row3-start; grid-column-start: col2-start; grid-row-end: row3-end; grid-column-end: col3 -end; )

Named lines can be either explicit or implicit. Implicit named lines are created whenever you create named grid areas using grid-template-areas .

The name is taken from the grid area with -start and -end added at the end, depending on whether it is the beginning or the end of the line.

Thus, for each grid area named header, four implicit lines will be created. Two are named header-start and column-start in the named grid area and two are named header-end respectively.

Named grid areas

Grid areas can be named in the grid-template-areas property of the grid container itself. This is what we did before when we created the site template. To restore this in memory, it looks like this:

#grid ( display: grid; /* Name the grid area */ grid-template-areas: “a a” “b c”; ... ) ... /* Now apply each grid element to the named grid area */ #a ( grid-area: a; ) #b ( grid-area: b; ) #c ( grid-area: c; )

You can indicate an empty cell by using a period (.) or a series of periods without spaces. For example:

Grid-template-areas: “a a” “. b"; Or grid-template-areas: “header header” “... content”;

Grid Placement Properties

There are three short properties that can be used in place of the long grid layout properties mentioned in the examples above. This is where they all fit.

grid-area - This property is shorthand for:

grid-column - This property is shorthand for:

grid-column-start — indicates which column line of the grid element is starting and how many tracks it extends to.

grid-column-end  — indicates which column lines the grid element ends on and how many tracks it extends to.

grid-row — this property is shorthand for:

grid-row-start — indicates which row line the grid element starts from and how many tracks it extends to.

grid-row-end  - indicates which row line will be the last for the element and how many tracks it will stretch.

You can also use the grid-auto-flow property, which was mentioned in the chapter before this one. It specifies how automatically placed grid elements should be placed in the grid. Automatically placed elements are those that are not explicitly placed using any of the properties above.

Create a nested grid

Grid elements can themselves become grids in CSS Grid. That is, you can nest a grid element within another grid element, thereby creating a nested grid.

To create such a nested grid, all you have to do is apply display: grid (or display: inline-grid) to the grid element and it becomes a grid itself. You can also use display: subgrid to create a subgrid. , How does this happen.

Example

1
2
3
5
6
7
8

Inheritance

Most grid properties are not inherited, which means that your nested grid will not inherit the values ​​of its parent grid. This allows you to make changes to the parent grid without unintentionally affecting the child grid.

For example, you set grid-auto-flow: column on the parent grid, but you did not set the property on the nested grid. In this case, the nested grid will be set to row because that is the initial value for this property.

Example

1
2
3
5
6
7
8

Note that on the parent grid, the numbers go vertically down the columns instead of horizontally along the row, but the nested grid still goes horizontally along the row.

Subgrids

The CSS Grid module sets the subgrid value for the display property. However, not all browsers support it yet. This value should prove quite useful.

Subgrid is a nested grid, but with display: subgrid . This makes it a special type of grid container that participates in setting the grid size of the parent grid container. In other words, the content of the subgrid influences the size of the parent grid, allowing content to be spread across two grids. Below is an example of where this property could be useful.

Here is the list of elements:

And here is CSS, where the list is a grid, and the list elements are subgrids.

Ul ( display: grid; grid: auto-flow / auto 1fr; ) li ( display: subgrid; grid-column: span 2; margin: 0.5em; border: solid; padding: 0.5em; ) label ( grid-column: 1; ) input ( grid-column: 2; )

This example would show the label and input in a row, with a border around each list item. Giving each list element a subgrid means that there should not be any problems with the alignment of input forms, because each list element will participate in shaping the size of the parent grid.

Auto-placement forms

You can use explicit grids as an advantage when creating forms or any other collection of elements that require grid alignment. For example, you can use explicit grids to create a form like this:

And as you add form elements to your markup, the explicit grid will add rows to accommodate them. So to create the shape on top, we need this markup.

There is no need for additional markings to arrange everything correctly. And also there is no need to add additional classes for form elements. We are adding only one class for

element, but even this is optional. Here's a working example:

Example

You can automatically add new form elements and they will automatically adjust to others, as they will be placed in an explicit grid.

This is possible because we made the form itself a grid (display: grid applied to .myForm). And then they indicated that labels go in one column, and controls in another.

Here's another example, this time with even more elements:

Example

Which taxi do you require?
Extras

Once subgrids become widespread among browsers, it will be possible to align form elements that are not direct descendants of

. For example, such as lists of form elements.

CSS Grid Alignment

In general, most alignment properties work the same on grid elements as on other elements. But there are also some alignment properties that only apply to grids and flexes.

The align-items property specifies the standard align-self value for all grid elements participating in the grid container in the context of its formatting.

align-items: center;

In the example above, we are using align-items: center for the grid container, therefore all grid elements will be aligned to the center of the block axis.

But since this is the default, any of the grid elements can override it using the align-self property.

Align-self property

This property aligns an element within a container block along the block/column/cross axes.

Red ( background: orangered; height: 40%; align-self: baseline; ) .green ( background: yellowgreen; height: 60%; ) .blue ( background: steelblue; height: auto; align-self: stretch; )

place-items property

This property is a shorthand for justify-items and align-items .

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






2024 gtavrl.ru.