CSS Grid 中的自动列宽:`auto-fill` 与 `auto-fit` 的区别
One of the most powerful and convenient CSS Grid features is that, in addition to explicit column sizing, we have the option to repeat-to-fill columns in a Grid, and then auto-place items in them. More specifically, our ability to specify how many columns we want in the grid and then letting the browser handle the responsiveness of those columns for us, showing fewer columns on smaller viewport sizes, and more columns as the screen estate allows for more, without needing to write a single media query to dictate this responsive behavior.
CSS Grid 最强大、最方便的特性之一是:除了可以显式设置列宽,我们还可以选择在网格中重复填充列,然后自动把项目放进去。更具体地说,我们可以指定网格中想要的列数,然后让浏览器负责这些列的响应式:在较小视口尺寸下显示更少列,在屏幕空间允许时显示更多列,而无需写一条媒体查询来规定这种响应行为。
We’re able to do that using just one line of CSS — the one-liner that reminds me of when Dumbledore just waved his wand in Horace’s apartment and “the furniture flew back to its original places; ornaments reformed in midair, feathers zoomed into their cushions; torn books repaired themselves as they landed upon their shelves…”.
我们只需一行 CSS 就能做到这一点——这一行让我想起了 Dumbledore 在 Horace 的公寓里挥动魔杖时的场景:“家具飞回原位;装饰品在半空中重组,羽毛嗖地飞回靠垫;撕裂的书籍在落回书架时自行修复……”。
This magical, media-query-less responsiveness is achieved using the repeat()
function and the auto-placement keywords.
这种无需媒体查询的神奇响应式效果,是通过 repeat()
函数和自动放置关键字实现的。
To summarize, the repeat()
function allows you to repeat columns as many times as needed. For example, if you’re creating a 12-columns grid, you could write the following one-liner:
简而言之,repeat()
函数允许你按需重复列。例如,如果你要创建一个 12 列的网格,可以写成下面这一行:
.grid { display: grid; grid-template-columns: repeat(12, 1fr);
}
The 1fr
is what tells the browser to distribute the space between the columns so that each column equally gets one fraction of that space. That is, they’re all fluid, equal-width columns. And the grid will, in this example, always have 12 columns regardless of how wide it is. This, as you have probably guessed, is not good enough, as the content will be too squished on smaller viewports.
1fr
告诉浏览器把空间均分给各列,使每列获得相等的一份空间。也就是说,它们都是等宽且自适应的列。在这个例子里,无论容器多...