CSS Grid 中的等宽列 [英] Equal width columns in CSS Grid

查看:57
本文介绍了CSS Grid 中的等宽列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让下面的 html 显示在 n 个相等的列中,无论使用 css 网格的行元素有两个、三个或更多子元素 - Flexbox 使这很容易,但我无法使用 css 网格完成它- 任何帮助表示赞赏.

I'd like to have the html below showing in n equal columns whether there are two, or three, or more child elements to the row element using css grid - Flexbox makes this easy but I cannot get it done using css grid - any help is appreciated.

<div class="row">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

推荐答案

TL;DR

grid-auto-columns: minmax(0, 1fr);
grid-auto-flow: column;

repeat(3, 1fr) 的常见答案并不完全正确.

The common answer of repeat(3, 1fr) is not quite correct.

这是因为 1fr 是关于可用(!)空间的分配.一旦内容变得大于轨道大小,这就会中断.默认情况下,它不会溢出并相应地调整列宽.这就是为什么不是所有 1fr 都保证宽度相等的原因.1fr 实际上只是 minmax(auto, 1fr) 的简写.

This is because 1fr is about the distribution of available(!) space. This breaks as soon as the content becomes bigger than the track size. By default, it does not overflow and adjust the column width accordingly. That's why not all 1fr are guaranteed to be of equal width. 1fr is actually rather just a shorthand for minmax(auto, 1fr).

如果您确实需要列的宽度与您应该使用的精确相同:

If you really need the columns to be the exact same width you should use:

grid-template-columns: repeat(3, minmax(0, 1fr));

minmax(0, 1fr) 允许网格轨迹小到 0 但大到 1fr,创建的列将保持平等.但是请注意,如果内容大于列或无法换行,这将导致溢出.

minmax(0, 1fr) allows the grid tracks to be as small as 0 but as large as 1fr, creating columns that will stay equal. But, be aware that this will cause overflows if the content is bigger than the column or cannot be wrapped.

这里有一个一个例子来展示差异.

Here is an example that demonstrates the difference.

最后,作为 @wegry@zauni 指出,要使其适用于任意数量的子列,您可以利用 grid-auto-columnsgrid-auto-flow 并使用它:

Finally, as @wegry and @zauni pointed out, to make it work for any number of child columns, you can take advantage of grid-auto-columns and grid-auto-flow and use this:

grid-auto-columns: minmax(0, 1fr);
grid-auto-flow: column;

这篇关于CSS Grid 中的等宽列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆