css 网格布局

tech2022-08-17  121

css 网格布局

The following introduction to CSS Grid is an extract from Tiffany’s book, CSS Master, 2nd Edition.

以下CSS Grid简介摘自Tiffany的书CSS Master,第二版 。

CSS Grid is a relatively recent layout specification, shipping in most browsers as of October 2017. Grid allows us to create layouts that were previously impossible, or only possible with lots of DOM operations.

CSS Grid是一个相对较新的布局规范,自2017年10月起已在大多数浏览器中提供。Grid使我们能够创建以前无法实现的布局,或者仅通过许多DOM操作才可能实现的布局。

Keep in mind that the CSS Grid specification is dense, and introduces several new concepts that are quite complex. Consider this an overview rather than a comprehensive look at Grid. Don’t worry, we’ll point you to lots of resources for learning more.

请记住, CSS Grid规范是密集的,并引入了一些非常复杂的新概念。 认为这是概述,而不是对Grid的全面了解。 不用担心,我们会为您提供大量资源,以了解更多信息。

网格格式上下文 (The Grid Formatting Context)

Adding display: grid to an element triggers a grid formatting context for that element and its children. In a grid formatting context, three things happen:

在元素上添加display: grid会触发该元素及其子元素的网格格式化上下文。 在网格格式环境中,发生三件事:

The element becomes a block-level element that participates in the normal flow.

该元素成为参与正常流程的块级元素。

Its children—whether elements or text nodes—create block-like, grid-level boxes that can be arranged into rows and columns. Immediate children of a grid container are grid items.

它的子级(无论是元素还是文本节点)都会创建可排列成行和列的块状,网格级别的框。 网格容器的直接子元素是网格项目 。

In a horizontal writing mode, each member in a grid row will have the same height as its tallest element (as determined by content), unless an explicit height value is set. When the document uses a vertical writing mode, it takes on the same length as its longest element (as determined by content).

在水平书写模式下,除非设置了明确的高度值,否则网格行中的每个成员将具有与其最高元素相同的高度(由内容确定)。 当文档使用垂直书写模式时,其长度与最长元素相同(由内容决定)。 Using 使用 display: grid creates a block-level container, and block boxes for its children display: grid创建一个块级容器,并为其子级创建块框

Using display: inline-grid works similarly. Children of inline-level grid containers create grid-level boxes, but the container itself participates in an inline formatting context.

使用display: inline-grid工作方式与此类似。 内联级网格容器的子级会创建网格级框,但是容器本身会参与内联格式设置上下文。

Using 使用 display: inline-grid creates an inline-level box for the container, but block boxes for its children display: inline-grid为容器创建一个内联级别的框,但为其子级创建一个框

By themselves, display: grid and display: inline-grid won’t automatically arrange these boxes into rows and columns. We also need to tell the browser where and how to place things.

单独display: grid和display: inline-grid不会自动将这些框排列成行和列。 我们还需要告诉浏览器在何处以及如何放置事物。

Before creating your grid, determine whether you want a fixed number of columns and/or rows, whether you’d like the browser to calculate the number of columns and rows automatically, or whether you’d like a mix of the two. Knowing what kind of grid you want to create determines the approach you’ll take. Let’s look at a few techniques.

在创建网格之前,请确定是否要使用固定数量的列和/或行,是否要让浏览器自动计算列和/或行的数量,或者是否要将两者混合使用。 了解要创建哪种网格将决定您要采用的方法。 让我们看一些技巧。

定义网格布局 (Defining a Grid Layout)

After defining a grid container, we’ll need to tell the browser how many rows and columns our grid should contain. We can define the number of rows and columns using the grid-template-rows and grid-template-columns properties. They’re applied to the grid container.

定义网格容器后,我们需要告诉浏览器网格应包含多少行和多少列。 我们可以使用grid-template-rows和grid-template-columns属性定义行数和列数。 它们已应用于网格容器。

Both grid-template-rows and grid-template-columns accept what’s known as a track list. The track list is a space-separated string that specifies grid line names and sizes of each position in the row or column.

grid-template-rows和grid-template-columns接受所谓的跟踪列表 。 跟踪列表是用空格分隔的字符串,用于指定网格线的名称以及行或列中每个位置的大小。

Each value in a track list creates a new space—a track—within the row or column. You can use lengths, flexible length units (discussed later in this chapter), or percentages. You can also use sizing values such as auto, min-content and max-conent.

轨道列表中的每个值都会在行或列内创建一个新空间- 轨道 。 您可以使用长度,弹性长度单位(在本章后面讨论)或百分比。 您还可以使用大小值,例如auto , min-content和max-conent 。

.grid { display: grid; grid-template-columns: 25rem 25rem 25rem; grid-template-rows: 10rem 10rem; }

In the code above, we’ve defined a grid with three columns, each 25rem units wide and two rows, each 10rem units tall. Let’s apply it to the following HTML. Yes, this is all the markup required:

在上面的代码中,我们定义了一个网格,该网格具有三列,每列宽25rem单位,两行,每行高10rem 。 让我们将其应用于以下HTML。 是的,这就是所有需要的标记:

<div class="grid"> <div>Grid item A</div> <div>Grid item B</div> <div>Grid item C</div> <div>Grid item D</div> <div>Grid item E</div> </div>

Our grid items get organized into the columns and rows shown below.

我们的网格项目被组织为以下所示的列和行。

Creating an explicit grid with grid-template-columns and grid-template-rows grid-template-columns和 grid-template-rows创建一个显式网 grid-template-columns

Here, we’ve created a grid of evenly sized rows and columns, but that isn’t a requirement of Grid. Let’s tweak our CSS slightly. We’ll change the value of grid-template-columns to 25rem 15rem 25rem:

在这里,我们创建了一个具有均匀大小的行和列的网格,但这不是Grid的要求。 让我们稍微调整一下CSS。 我们将grid-template-columns的值更改为25rem 15rem 25rem :

.grid { display: grid; grid-template-columns: 25rem 15rem 25rem; grid-template-rows: 10rem 10rem; }

Now the second column in our grid is narrower than the first and third.

现在,网格中的第二列比第一列和第三列窄。

Grid columns and rows don’t have to be the same width 网格列和行的宽度不必相同

显式网格与隐式网格 (Explicit Grid versus Implicit Grids)

In the previous section, we explicitly stated that this grid should have six available grid cells formed by three columns and two rows. This is what’s known as an explicit grid. Here, our grid container only has five children. The remaining position is empty. Let’s see what happens when we add more children to the container.

在上一节中,我们明确声明此网格应具有由三列两行组成的六个可用网格单元。 这就是所谓的显式网格 。 在这里,我们的网格容器只有五个子代。 其余职位为空。 让我们看看将更多的子代添加到容器时会发生什么。

When grid items exceed the number of explicitly defined cells, the remaining items are arranged in an implicit grid 当网格项目超过显式定义的单元格的数量时,其余项目将排列在隐式网格中

Now we have three rows. Notice, however, that our third row is only as tall as its contents and padding. It’s part of the grid because these items are the children of a grid container. Yet the row isn’t explicitly defined by grid-template-rows. What we have instead is an implicit grid—an explicit grid with additional grid items that exceed the defined number of explicit grid cells.

现在我们有三行。 但是请注意,我们的第三行仅与内容和填充一样高。 它是网格的一部分,因为这些项目是网格容器的子级。 然而,并没有由grid-template-rows明确定义grid-template-rows 。 相反,我们拥有的是隐式网格 -显式网格,其中的其他网格项超过了定义的显式网格单元数。

Items within an implicit grid are auto sized by default. Grid items will expand to accommodate their contents, or fill the remaining vertical space in the container—whichever is taller. If, for example, we set the height property of our container to 50rem, our implicit grid track will expand to be 30rem tall.

默认情况下,隐式网格中的项目会auto调整大小。 网格项目将扩展以容纳其内容,或填充容器中剩余的垂直空间(以较高者为准)。 例如,如果我们将容器的height属性设置为50rem ,则隐式网格轨迹将扩展为30rem高。

Implicit grid rows expand to fill the available height of the container 隐式网格行扩大以填充容器的可用高度

If we add enough items to create a fourth row, the height of our implicit grid items will be distributed evenly across the remaining 30rem of vertical space in the container. Their computed height will be 15rem each.

如果我们添加足够的项目以创建第四行,则隐式网格项目的高度将在容器中剩余的30rem垂直空间中均匀分布。 它们的计算高度各为15rem 。

The height of implicit grid rows will be evenly distributed based on the remaining space in the grid container 隐式网格行的高度将根据网格容器中的剩余空间均匀分布

In our original example, we’ve explicitly defined only two rows with a height of 10rem each, so our third row defaults to auto sizing. Its height will adjust to the size of its contents and padding.

在原始示例中,我们仅明确定义了两行,每行的高度均为10rem ,因此第三行默认为auto调整大小。 它的高度将根据其内容和填充的大小进行调整。

为隐式网格指定轨道大小 (Specifying Track Size for an Implicit Grid)

It is possible, however, to set a kind of explicit, default height or width for implicit grid items using the grid-auto-rows and grid-auto-columns properties. Let’s update our CSS with grid-auto-rows:

但是,可以使用grid-auto-rows和grid-auto-columns属性为隐式网格项目设置一种显式的默认高度或宽度。 让我们用grid-auto-rows更新我们CSS:

.grid { display: grid; grid-template-columns: 25rem 15rem 25rem; grid-template-rows: 10rem 10rem; grid-auto-rows: 30rem; }

Now items in our third row—and any subsequent rows—will be 30rem in height.

现在,第三行以及以后的所有行中的30rem的高度将为30rem 。

Using 使用 grid-auto-rows to specify the height of implicit grid items grid-auto-rows指定隐式网格项的高度

There’s one drawback to using the grid-auto-* properties: when the contents of a grid item exceed its dimensions, they will overflow the container (shown below), and may be clipped visually by elements in other rows.

使用grid-auto-*属性有一个缺点:当网格项目的内容超过其尺寸时,它们将使容器溢出(如下所示),并可能被其他行中的元素可视地剪切。

Contents of a grid container can overflow the container when using length or percentage units 使用长度或百分比单位时,网格容器的内容可能会使容器溢出

One way to avoid this is to use the minmax() function. Let’s rewrite our CSS to use minmax():

避免这种情况的一种方法是使用minmax()函数。 让我们重写CSS以使用minmax() :

.grid { display: grid; grid-template-columns: 25rem 15rem 25rem; grid-template-rows: 10rem 10rem; grid-auto-rows: minmax(30rem, auto); }

As you may have guessed from its name, minmax() lets us define the minimum and maximum size of a track. It requires two arguments, the first of which is the minimum desired track size. The second argument is the maximum desired size.

正如您可能从其名称中猜到的那样, minmax()可让我们定义轨道的最小和最大大小。 它需要两个参数,第一个是所需的最小轨道尺寸。 第二个参数是所需的最大大小。

In this case, our row will be at least 30rems high. But since we’ve set our maximum size to auto, our track will expand to accommodate the content of that cell. Arguments for minmax() can be lengths or percentages, or one of the auto, min-content, and max-content keywords. Here, minmax(30rem, max-content) would achieve much the same effect. Flexible units, discussed in the next section, are also valid.

在这种情况下,我们的行的高度至少为30rems 。 但是,由于我们将最大尺寸设置为auto ,因此我们的轨道将扩展为容纳该单元格的内容。 minmax()参数可以是长度或百分比,也可以是auto , min-content和max-content关键字之一。 在这里, minmax(30rem, max-content)将达到几乎相同的效果。 下一部分讨论的灵活单位也有效。

Lengths and percentages can be used to define track sizes. Using them may mean that the grid items don’t fill the entire width or height of the container. For example, if our grid container is 70rem wide, grid-template-columns: 25rem 15rem 25rem; will only fill about 90% of its horizontal space. On the other hand, if our grid container is only 50rem wide, the total width of our columns will overflow the container’s bounds.

长度和百分比可用于定义轨道大小。 使用它们可能意味着网格项不会填充容器的整个宽度或高度。 例如,如果我们的网格容器的宽度为70rem ,则grid-template-columns: 25rem 15rem 25rem; 仅会填充其水平空间的90%。 另一方面,如果网格容器的宽度仅为50rem ,则列的总宽度将使容器的边界溢出。

One way to avoid this issue is by using flexible length units.

避免此问题的一种方法是使用灵活的长度单位。

使用弹性单元创建弹性网格 (Creating Flexible Grids with Flex Units)

Flexible length or flex units are best understood as fractional units, and are expressed using fr. Flex units indicate to the browser what fraction or proportion of the leftover space in a grid container should be allocated to each grid item. They’re a ratio, not a true length value in the way px, em, or cm are.

弹性长度或弹性单位最好理解为分数单位,并使用fr表示。 伸缩单位向浏览器指示应将网格容器中剩余空间的哪个部分或比例分配给每个网格项。 它们是一个比率,不是px , em或cm的真实长度值。

There’s a formula for calculating the used width of an item when using flexible units: (flex × leftover space) &div; sum of all flex factors. If, for instance, our grid container is 1000px wide, and the value of grid-template-columns is 3fr 2fr 1fr, our columns will be 500px, 333.33px and 133.33px wide. The width of each column is allocated proportionally from the space available, as shown below.

有一个公式可以计算使用弹性单位时所用物品的宽度: (flex×剩余空间)&div; 所有弹性因子之和 。 例如,如果我们的网格容器为1000px宽,并且grid-template-columns值为3fr 2fr 1fr ,则我们的列将分别为500px , 333.33px和133.33px宽。 每一列的宽度从可用空间中按比例分配,如下所示。

Flexible length units maintain grid proportions, rather than absolute lengths 灵活的长度单位保持栅格比例,而不是绝对长度

Because these units are ratios and not absolute lengths, grid-template-columns: 2fr 2fr 2fr is equivalent to grid-template-columns: 1fr 1fr 1fr. Both will result in columns of equal width for horizontal writing modes, and rows of equal height for vertical writing modes.

因为这些单位是比率,而不是绝对长度,所以grid-template-columns: 2fr 2fr 2fr等效于grid-template-columns: 1fr 1fr 1fr 。 对于水平书写模式,这两者将导致宽度相等的列,对于垂直书写模式,将导致高度相等的行。

Note: fr units are not true length values. This makes them incompatible with other length units, such as px and rem and width percentages. It also means that you can’t use fr units with the calc() function. For example, calc(1fr - 1rem) is an invalid length value.

注意: fr单位不是真实长度值。 这使它们与其他长度单位(例如px和rem和宽度百分比)不兼容。 这也意味着您不能在calc()函数中使用fr单位。 例如, calc(1fr - 1rem)是无效的长度值。

使用grid-template速记属性 (Using the grid-template Shorthand Property)

We can also indicate the number of rows and columns using the grid-template property. Its syntax is as follows:

我们还可以使用grid-template属性指示行数和列数。 其语法如下:

grid-template: [row track list] /

Consider this block of CSS:

考虑一下这段CSS:

.grid { display: grid; grid-template-columns: 25rem 25rem 25rem; grid-template-rows: 10rem 10rem; }

We can combine the second and third lines using grid-template:

我们可以使用grid-template组合第二行和第三行:

.grid { display: grid; grid-template: 10rem 10rem / 25rem 25rem 25rem; }

For clarity, however, you may still wish to use the longhand properties.

但是,为清楚起见,您可能仍希望使用longhand属性。

重复行和列 (Repeating Rows and Columns)

In many cases, you’ll want grid columns or rows that repeat automatically; think of a list of store items or recipe search results. Grid offers a syntax for that—the repeat() function:

在许多情况下,您会希望网格列或行自动重复; 想一想商店商品或食谱搜索结果的列表。 Grid为此提供了一种语法repeat()函数:

.grid { display: grid; grid-template-columns: repeat(3, 1fr); }

repeat() accepts two arguments:

repeat()接受两个参数:

the number of times to repeat the track list

重复曲目列表的次数 a track list to repeat

重复的曲目列表

Arguments must be separated by a comma. The first argument may be a positive integer, or the auto-fit or auto-fill keywords. The above CSS produces the following grid. Our 1fr track list is repeated three times.

参数必须用逗号分隔。 第一个参数可以是正整数,也可以是auto-fit或auto-fill关键字。 上面CSS产生以下网格。 我们的1fr曲目列表重复了3次。

A repeating grid with 带有 fr units fr单位的重复网格

We could also use a two-column pattern that repeats twice. For example, grid-template-columns: repeat(2, 1fr 3fr); produces a four-column grid. As the image below shows, the first and third columns are one third the width of the second and fourth. In both cases, the value of grid-template-rows is auto.

我们还可以使用重复两次的两列模式。 例如, grid-template-columns: repeat(2, 1fr 3fr); 产生一个四列网格。 如下图所示,第一和第三列的宽度是第二和第四列的宽度的三分之一。 在这两种情况下, grid-template-rows的值都是auto 。

A repeating two-column grid pattern 重复的两列网格图案

重复使用列auto-fit或auto-fill (Repeating Columns with auto-fit or auto-fill)

Both of the preceding examples tell the browser: here’s a track list pattern; please repeat it X number of times. What you may want to tell the browser instead, though, is: please fit as many columns or rows as you can within this grid container. For that, we can use auto-fit or auto-fill as the first argument for repeat(), in combination with minmax().

前面的两个示例都告诉浏览器: 这是一个跟踪列表模式; 请重复X次 。 但是,您可能想告诉浏览器的是: 请在此网格容器内尽可能多地容纳列或行 。 为此,我们可以将auto-fit或auto-fill与minmax()结合用作repeat()的第一个参数。

What’s the difference between auto-fit and auto-fill? It’s subtle, but significant.

auto-fit和auto-fill什么区别? 这很微妙,但意义重大。

auto-fill fits as many grid items as it can within a track line, adding anonymous grid tracks if necessary.

auto-fill会在一条跟踪线内尽可能多地容纳网格项目,并在必要时添加匿名网格跟踪 。

auto-fit fits as many grid items as it can within a track line, expanding or collapsing the dimensions of each track if necessary.

auto-fit可在一条轨迹线内尽可能多地auto-fit网格项目,并在必要时扩展或折叠每个轨迹的尺寸 。

This difference becomes apparent when the grid container’s width exceeds the maximum total width of its grid items. Let’s compare some CSS:

当网格容器的宽度超过其网格项目的最大总宽度时,这种差异变得明显。 让我们比较一些CSS:

.grid { display: grid; width: 800px; } .autofill { grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); } .autofit { grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); }

And let’s apply this CSS to the HTML below:

让我们将此CSS应用于以下HTML:

<div class="grid autofill"> <div>Grid item A</div> <div>Grid item B</div> <div>Grid item C</div> <div>Grid item D </div> <div>Grid item E</div> </div> <div class="grid autofit"> <div>Grid item A</div> <div>Grid item B</div> <div>Grid item C</div> <div>Grid item D </div> <div>Grid item E</div> </div>

The only difference between these two grid layouts is that one uses auto-fill and the other uses auto-fit. But compare the two grids in the image below.

这两种网格布局之间的唯一区别是,一种使用auto-fill ,另一种使用auto-fit 。 但是,请比较下图中的两个网格。

Comparing 将 auto-fill with auto-fill与 auto-fit auto-fit

In both grids, the total maximum width of the grid items is less than that of the grid container. However, in the top grid—our auto-fill grid—that excess space is filled in by anonymous grid items.

在两个网格中,网格项目的总最大宽度小于网格容器的总宽度。 但是,在顶部网格(我们的auto-fill网格)中,多余的空间由匿名网格项填充 。

Visualizing the difference between 可视化 auto-fill to auto-fill与Firefox网格检查器 auto-fit with the Firefox grid inspector auto-fit之间的区别

Compare that to the bottom grid, in which each grid item has been stretched to fit the available space. The image above illustrates what those anonymous grid cells look like using Firefox’s developer tools.

将其与底部网格进行比较,底部网格中的每个网格项目均已拉伸以适合可用空间。 上图显示了使用Firefox开发人员工具的那些匿名网格单元的外观。

Note: If this still doesn’t make any sense, read Sara Soueidan’s “Auto-Sizing Columns in CSS Grid: auto-fill vs auto-fit”. It contains some video examples that illustrate the difference a little bit better than static images can.

注意:如果仍然没有任何意义,请阅读Sara Soueidan的“ CSS Grid中的自动调整列大小: auto-fill与auto-fit ”。 它包含一些视频示例,这些示例比静态图像更好地说明了差异。



This is an extract from the book CSS Master, 2nd Edition. Up to this point, we’ve covered simple grids that are neatly aligned rows and columns of boxes. The book goes on to explain the far more complex layouts Grid can handle, covering line-based grid placement, named grid areas, how to space grid items, and dealing with images within grids.

这摘自《 CSS Master,第二版 》一书。 到目前为止,我们已经介绍了简单的网格,这些网格整齐地对齐了框的行和列。 本书继续解释了Grid可以处理的更为复杂的布局,包括基于行的网格放置,命名的网格区域,如何对网格项进行空间划分以及如何处理网格中的图像。

结论 (Conclusion)

CSS Grid is a very dense topic. We’ve really just scratched the surface here. Luckily, there’s a wealth of resources that can help you learn more.

CSS Grid是一个非常密集的主题。 我们真的只是在这里刮了一下表面。 幸运的是,这里有大量资源可以帮助您了解更多信息。

I believe in reading specifications where possible. In my opinion, the CSS Grid specification is quite readable, and it’s a good place to begin your own explorations of grid layout. But specifications do tend to contain a lot of jargon, because they’re targeted not only at web developers, but also those tasked with implementing the specification in browsers.

我相信尽可能阅读规范。 在我看来, CSS Grid规范具有很好的可读性,并且是开始自己探索网格布局的好地方。 但是规范确实包含很多术语,因为它们不仅针对Web开发人员,而且还针对那些在浏览器中实现规范的人员。

Rachel Andrew’s Grid by Example was created for a web developer audience. The site includes grid layout tutorials and a collection of common user interface patterns. Be sure to visit the site’s Resources section too. It’s a cornucopia of links that demonstrate what you can do with CSS Grid.

雷切尔·安德鲁(Rachel Andrew)的Grid by Example是为Web开发人员创建的。 该站点包括网格布局教程和常见用户界面模式的集合。 确保也访问该站点的“ 资源”部分。 这是链接的聚宝盆,这些链接演示了可以使用CSS Grid进行的操作。

Jen Simmons’ Experimental Layout Lab is also chock-full of examples that illustrate Grid’s possibilities. If video is more your style, Simmons’ Layout Land YouTube channel includes video walkthroughs of grid and other layout topics.

詹·西蒙斯(Jen Simmons)的“实验版图实验室”( Experimental Layout Lab)中也有很多示例,这些示例说明了Grid的可能性。 如果您更喜欢视频,Simmons的Layout Land YouTube频道将提供有关网格和其他布局主题的视频演练。

When you need more of a cheatsheet-style reference, try “A Complete Guide to Grid”, by CSS-Tricks.

如果您需要更多备忘单样式的参考,请尝试CSS-Tricks撰写的“ 网格的完整指南 ”。

翻译自: https://www.sitepoint.com/creating-css-grid-layouts/

css 网格布局

最新回复(0)