Html CSS Grid 中的等宽列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47601564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Equal width columns in CSS Grid
提问by user1678736
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.
我想让下面的 html 显示在 n 个相等的列中,是否有两个、三个或更多子元素到使用 css 网格的行元素 - Flexbox 使这很容易,但我无法使用 css 网格完成它 - 任何帮助被赞赏。
<div class="row">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
回答by Kevin
Define this on your grid container. Sets up three columns of equal width.
在您的网格容器上定义它。设置三列等宽。
grid-template-columns: repeat(3, 1fr);
回答by wegry
@Michael_B's answer is almost there.
@Michael_B 的回答差不多了。
.grid-container {
display: grid;
grid-auto-columns: 1fr;
grid-auto-flow: column;
}
Gives you one row of equally sized columns in Chrome, Firefox, and Safari as of writing.
在撰写本文时,在 Chrome、Firefox 和 Safari 中为您提供一行大小相同的列。
回答by tcurdt
The common answer of repeat(3, 1fr)
is not quite correct.
的常见答案repeat(3, 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)
.
这是因为这1fr
是关于可用(!)空间的分布。一旦内容变得大于轨道大小,这就会中断。默认情况下,它不会溢出并相应地调整列宽。这就是为什么不是所有的1fr
都保证宽度相等的原因。1fr
实际上只是minmax(auto, 1fr)
.
If you really need the columns to be the exactsame width you should use:
如果您确实需要列的宽度完全相同,则应使用:
grid-template-columns: repeat(3, minmax(0, 1fr));
But be aware that this will cause overflows if the content is bigger than the column or cannot be wrapped.
但请注意,如果内容大于列或无法换行,这将导致溢出。
Here is an examplethat demonstrates the difference.
回答by Michael Benjamin
Try this:
尝试这个:
.grid-container {
display: grid;
grid-auto-columns: 1fr;
}
.grid-items {
grid-row: 1;
}
Otherwise, here's a demo that may be useful: jsFiddle
否则,这里有一个可能有用的演示:jsFiddle
To learn about the fr
unit, see these posts:
要了解该fr
单元,请参阅以下帖子:
回答by Alexis Vera
This allows the columns to distribute better, and the columns are the same size regardless of whether the size of the items does not adjust.
这样可以让列更好的分布,不管item的大小不调整,列的大小都是一样的。
.row {
display: grid;
grid-template-columns: repeat( auto-fit, minmax(33.33%, 1fr) );
}
.item {
grid-column: span 1;
}