1fr 1fr 对比 auto auto 对比 50% 50%

Are these columns the same?

这些列是一样的吗?

.grid { display: grid; grid-template-columns: 1fr 1fr; grid-template-columns: 50% 50%; grid-template-columns: auto auto; }Code language: CSS (css)

.grid { display: grid; grid-template-columns: 1fr 1fr; grid-template-columns: 50% 50%; grid-template-columns: auto auto; }代码语言:CSS (css)

I mean, obviously they aren’t literally the same, but you also probably won’t be surprised that they have different behavior as well. And yet…. they do kinda basically do the same thing. Two equal width columns.

我的意思是,显然它们并不完全相同,但你也可能不会惊讶于它们的行为有所不同。然而……它们 确实 基本上做的是同样的事情。两个相等宽度的列。

A grid layout showcasing three different configurations: two columns with '50% 50%' width, two columns with 'auto auto', and two columns with '1fr 1fr', each containing minimal text.

Above is a screenshot of three different grids, using each of those different grid-template-columns I showed above. And indeed, they all seem to do the same thing: two equal width columns. I’ve put a red line down the middle and right edge of the container for illustration purposes.

上面是三个不同网格的截图,使用了我上面展示的每种不同的 grid-template-columns。确实,它们似乎都做了同样的事情:两个相等宽度的列。我在容器的中间和右边缘画了一条红线以作说明。

But things start to change as we do different things. For instance, if we apply some gap between the columns. Here’s the examples with 16px of gap applied:

但是当我们做不同的事情时,情况开始发生变化。例如,如果我们在列之间应用一些 gap。以下是应用了 16pxgap 的示例:

Screenshot showing three grid layouts side by side: the first has two equal width columns labeled '50% 50%', the second uses 'auto auto', and the third shows '1fr 1fr'. Each column contains a short text saying 'Very little text.' with a red line marking the division between columns. Gap is applied, so the first of them extends past the parent width.

Now the grid with grid-template-columns: 50% 50%; is busting outside of the container element. Sometimes we think of % units as being quite flexible, but here we’re rather forcefully saying each columns needs to be 50% as wide as it’s parent element, so the width of the whole grid is actually 50% + 16px + 50% which is wider than 100%.

现在,使用grid-template-columns: 50% 50%;的网格超出了容器元素的范围。有时我们认为%单位是相当灵活的,但在这里我们相当强硬地说每一列需要是其父元素宽度的50%,因此整个网格的宽度实际上是50% + 16px + 50%,这比100%更宽。

This is pretty awkward and largely why you don’t see columns set up using % values all that much. But it still can be valuable! The “sturdiness” of setting a column that way can be desirable, as we’ll see. If we wanted to prevent the “blowout”, we could account for the gap ourselves.

这相当尴尬,这也是为什么你不常看到使用%值设置的列。但这仍然是有价值的!以这种方式设置列的“坚固性”是可取的,正如我们将看到的。如果我们想防止“爆炸”,我们可以自己考虑间隙。

...
开通本站会员,查看完整译文。

inicio - Wiki
Copyright © 2011-2025 iteam. Current version is 2.144.0. UTC+08:00, 2025-06-14 21:25
浙ICP备14020137号-1 $mapa de visitantes$