使用任一auto-fill or auto-fit作为第一个参数repeat()符号。
<auto-repeat>的变体repeat()
符号:
repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
auto-fill
When auto-fill
给出重复次数,如果网格
容器有一个definite相关轴上的尺寸或最大尺寸,然后
重复次数是最大可能的正整数
这不会导致网格溢出其网格容器。
https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fill
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
网格将重复尽可能多的轨道,而不会溢出其容器。
在这种情况下,考虑到上面的例子(见图),只有 5 个轨道可以容纳网格容器而不溢出。我们的网格中只有 4 个项目,因此在剩余空间内创建第五个项目作为空轨道。
剩余空间的其余部分,轨道#6,结束显式网格。这意味着没有足够的空间放置另一条轨道。
auto-fit
The auto-fit
关键字的行为与auto-fill
, 除了
之后网格项目放置任何空的重复轨道都会被折叠。
https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fit
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
网格仍将重复尽可能多的轨道而不溢出其容器,但空轨道将折叠为0
.
折叠轨道被视为具有固定轨道大小函数0px
.
不像auto-fill
例如,空的第五个轨道被折叠,在第四个项目之后结束显式网格。
auto-fill
vs auto-fit
当minmax()使用函数。
Use minmax(186px, 1fr)
将项目范围从186px
to a 网格容器中剩余空间的一部分.
使用时auto-fill
,一旦没有空间放置空轨道,项目就会增长。
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
使用时auto-fit
,项目将增长以填充剩余空间,因为所有空轨道将折叠到0px
.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
操场:
CodePen
检查自动填充轨道
检查自动调整轨道