Understanding CSS Grid: Creating A Grid Container, by Rachel Andrew

This series introduces the CSS grid layout and is published in three parts. This is the first in a series.

  • Part 1: Create a grid container
  • Part 2: Grid lines
  • Part 3: Grid areas

After reading this article, you will learn:

  • usedisplay: griddisplay: inline-gridCreate a grid container.
  • usegrid-template-columnsgrid-template-rowsSet the rows and columns.
  • usegrid-auto-columsgrid-auto-rowsProperty sets the size of implicit tracks.

Create a container

Similar to elastic layouts, you need to create a grid container before using a grid layout. Grid containers can be created using display: grid. Grid layout elements created in this way behave as block-level elements and automatically generate a Grid formatting context, all of whose immediate children automatically become grid items.

But you won’t see results immediately, not because the layout doesn’t work. It’s because if you don’t have columns for the grid, the default layout is one column, with grid items stacked one on top of each other, acting like block elements.

“Block-like elements” can be a bit confusing, in order to prove that grid projects behave like blocky elements regardless of element type. Here’s an example:

<div class="grid">
  <div>Item one</div>
  <div>Item Two</div>
  A string of text with a <span>span element</span> in the middle.
</div>
This string of text follows the grid.

<style>
.grid { display: grid; }
</style>
Copy the code

A string of text with A span element in the middle. It looks like a line.

Let’s look at this in action (demo) :

Notice that the bare text on both sides of stands on separate lines. Using the Firefox Grid Inspector, you find five lines.

As you can see, grid projects take on the characteristics of blocky elements in the context of grid formatting, regardless of element type (even bare text nodes).

Of course, you can also create a grid using display: inline-grid. What’s the difference between a grid and an inline-grid? This is similar to the relationship between inline and inline-block. The inline-grid grid behaves externally as an inline element and can be placed in a row with other inline elements, while internally it behaves as a block element with width and height attributes.

As in the previous example, we changed the CSS slightly:

.grid {display: inline-grid; }
Copy the code

Here’s the result (demo) :

I can line up with the text that follows.

Rows and columns

To make the grid look like a grid, we need to set the rows and columns with grid-template-column and grid-template-rows. The values received by these two attributes are called track-list. Take a look at what the spec says:

These two attributes receive whitespace separated track lists, consisting of line Names and Track sizing functions. Grid-template-columns specifies the track list of grid columns, and grid-template-rows specifies the track list of grid rows.

Here are some valid track-list values:

grid-template-columns: 100px 100px 200px; Create a grid of three columns: the first column100pxThe second column,100pxAnd the third column200px.
grid-template-columns: min-content max-content fit-content(10em); Create a grid of three columns: the first columnmin-contentThe second column,max-contentThe third column does not exceed10em(If it’s for this orbitalmax-contentIs greater than10em; Otherwise the performance is no more thanmax-content).
grid-template-columns: 1fr 1fr 1fr; Create a three-column grid using fr units. Each grid column divides the available space equally, and each column gets 1/3 of the available space.
grid-template-columns: repeat(2, 10em 1fr); userepeat()The function creates a 4-column grid. Is equivalent to10em 1fr 10em 1fr, that is,10em 1frRepeat the result twice.
grid-template-columns: repeat(auto-fill, 200px); In the grid, as many as possible200pxThe width of columns. There will be a gap if there is any space left.
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); In the grid, as many as possible200pxThe wide columns fill the container. If there is any free space, divide the free space equally among each created column.
grid-template-columns: [full-start] 1fr [content-start] 3fr [content-end] 1fr [full-end]; Create a three-column grid: the first and third columns each have 1/5 of the available space, and the middle column has 3/5 of the available space. We name the grid lines by placing names in square brackets

As you can see, there are several ways to create a track list. Next, let’s look at how these values work. Also, there are some tips on why to use it this way.

Use length units

You can create tracks using units of length or percentage. If all the track sizes add up to less than the available size of the current container, the grid items are arranged by default on the left side of the container (under formatting rules for languages like English), leaving the extra space on the right. This is because the align-content and context-content properties default to start (demo).

Of course, you can also use functions like min-content, max-content keywords, and fit-content().

Min-content is the minimum size of the element without overflow. When applied to a column, it is equal to the size of the longest word in the column or the largest fixed-size element.

Max-content is the maximum size of the element’s content without folding at all. When applied to a column, it is equal to the expanded size of the text of the column without folding at all. Be aware of overflow problems that may occur when using.

Fit-content () is not used until a value is passed in. This value represents the maximum size that the orbit can grow to, and the orbit stops growing until it is free to extend beyond this critical point without folding. So, the result is that the orbital length is always less than the value passed in (as long as the value is between min-content and max-content).

Here’s an example:

<div class="grid">
  <div>Item One</div>
  <div>Item Two Item Two</div>
  <div>Item Three Item Three Item Three</div>
  <div>Item Four</div>
</div>

<style>
.grid {
  display: grid;
  grid-template-columns: min-content max-content fit-content(10em);
}
</style>
Copy the code

The result is as follows (demo) :

The third column stops growing once it reaches the size of 10em.

An overflow occurs if all the tracks take up more space than the container itself. Especially when setting track dimensions in percentage units, be careful that the total percentage does not add up to more than 100%, otherwise it will overflow.

frunit

There is another way to use the Grid to help you avoid using percentage values by manually calculating — fr units. It is not a unit of length and therefore cannot be used in calc(); it is used to represent the space available in the current grid container.

Take the track list 1FR 1FR 1FR for example: the available space is divided into three equal parts, and each track gets 1/3 of them. For 2FR, 1FR, 1FR, the second column and the third column both get a quarter of the free space, and the first column gets a half of the free space.

<div class="grid">
  <div>Item One</div>
  <div>Item Two Item Two</div>
  <div>Item Three Item Three Item Three</div>
  <div>Item Four</div>
</div>

<style>
.grid {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr;
}
</style>
Copy the code

Effect (Demo) :

It is important to note that the FR units are allocated avaible space, not the entire container space. If the grid track contains fixed-size elements or unfoldable words, these elements are laid out first, and then the remaining space (usable space) is reserved for FR allocation.

Another example — I removed the space between the word ItemThree in the third grid item, which resulted in a very long word. This time the layout, you have to consider it first.

The 1FR of the third item no longer works, the width is completely stretched by the content. The remaining available space is then allocated to the first and second projects, with the first project accounting for 2/3 and the second for 1/3.

You can also mix fr with other length units, which can be useful in some scenarios. For example, we have a three-column component where the two columns on each side are fixed in size and the middle column automatically fills the remaining space.

<div class="grid">
  <div>Fixed</div>
  <div>Flexible</div>
  <div>Fixed</div>
</div>

<style>
.grid {
  display: grid;
  grid-template-columns: 100px 1fr 100px;
}
</style>
Copy the code

Effect (Demo) :

Or you can set one track size to fit-Content (300px) and others to 1fr. This will make the first orbital no larger than 300px (occupying only the required space), while the orbital using FR will automatically expand the remaining space.

For example, if we place an image in the first track at max-width: 100%, the image will be at most 300px wide. Using this approach can create a very flexible component layout.

.grid {
  grid-template-columns: fit-content(300px) 1fr;
}
Copy the code

Effect (Demo) :

repeat()function

The repeat() function helps you avoid writing the same value over and over again. For example, the following two lines of code do the same thing:

grid-template-columns: 1.fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
grid-template-columns: repeat(12, 1fr);
Copy the code

The first argument of repeat() indicates the number of repeats, and the second argument is track list. Track List can use multiple values.

You can also use the repeat() function as part of the track list. For example, the following code creates one 1fr track, three 200px tracks, and one 1fr track.

grid-template-columns: 1.fr repeat(3200px1)fr
Copy the code

In addition to using a fixed number of repetitions, you can also use auto-fill and auto-fit keywords in repeat(). Using one of these instead of a fixed value written to the element, the grid container will have as many grid items in a row as possible (keeping each grid item at least 200px wide).

Code:

<div class="grid">
  <div>Item One</div>
  <div>Item Two</div>
  <div>Item Three</div>
  <div>Item Four</div>
</div>

<style>
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  width: 500px;
}
</style>
Copy the code

Effect (Demo) :

The grid container here has a fixed length (500px), both tracks are 200px, and the container cannot be completely divided, so there is some space left on the right.

Of course, we can use the function minmax(), where the first argument is the minimum acceptable value and the second argument is the maximum. We set the minimum size to 200px and the maximum size to 1fr so that if there is any space left, it will be filled up.

Code:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  width: 500px;
}
Copy the code

Effect (Demo) :

I mentioned two keywords earlier: auto-fill and auto-fit. If your content is more than one line, you won’t see the difference using these two keywords. The difference is when there’s only one line.

When auto-fill is used, new tracks are generated even if there is no more content in the grid container that can be typesetted.

<div class="grid">
  <div>Item One</div>
</div>

<style>
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  width: 500px;
}
</style>
Copy the code

Effect (Demo) :



auto-fit

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  width: 500px;
}
Copy the code

Effect (Demo) :

Using the Firefox Grid Inspector, you can see that the number of the last column is still 3, but the space has shrunk to 0 and is now the same as the second column. There are three columns, which means we can put two orbitals, but because the second one doesn’t have any space, the first one gets squeezed out.

Named grid line

As a final example we will look at the use of named gridlines. When using grid layouts, each grid line is numbered by default, and we can also name the grid lines. The name of the grid is defined in a pair of square brackets, and each grid line can have multiple names separated by Spaces. Here’s an example: The track list below has two names for each grid line.

grid-template-columns: [main-start sidebar-start] 1fr [sidebar-end content-start] 4fr [content-end main-end]
Copy the code

You can give grid lines any name except span, which is a reserved word and can be used when arranging grid items.

In the next article in this series, I’ll discuss how to lay out grid projects based on grid lines and how to use named grid lines.

Display and implicit grids

The grid area is set with grid-template-columns and grid-template-rows attributes. This is called the explicit grid. Because the track size in this grid area is explicitly set.

If the grid is large, beyond the area set by removing two properties, it is called an implicit grid. Grid items arranged in this area are rendered to their own size by default. How do you control these out-of-scope rows and columns using grid-auto-rows or grid-auto-columns? For example, if you want all the implicit grid columns to be at least 200px wide, and if there is more content, you can use the following declaration:

grid-auto-rows: minmax(200px.auto)
Copy the code

If you want odd lines to be naturally high, even lines to be 100px, or something else, try multivalued syntax.

grid-auto-rows: auto 100px
Copy the code

Effect (Demo) :

(End of text)


Advertising time (long term)

I have a good friend who owns a cattery, and I’m here to promote it for her. Now the cattery is full of Muppets. If you are also a cat lover and have the need, scan her FREE fish QR code. It doesn’t matter if you don’t buy it. You can just look at it.

(after)