目前,使用 grid-template-columns: repeat(auto-fit, minmax(25rem, 1fr));
行为如下:如果元素多于一行(基于最小值),则创建新行。如果元素数量少于行所能容纳的数量,则元素会扩展以填充剩余空间。
但是如果您不想让它们填满空间,但有一个最大尺寸怎么办?设置元素的 max-width 可以解决问题,但随后会将元素分散到整个容器中。如果网格比元素总数宽,我希望元素具有最大尺寸,而不是填充空间或在容器中间隔开。
这种行为可能吗?
片段显示网格>总元素
html {
font-size: 62.5%;
}
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(25rem, 1fr));
grid-template-rows: repeat(2, 20rem);
grid-gap: 1rem;
border: 1px solid lightgrey;
padding: 1rem;
}
.item {
background: lightblue;
// max-width: 35rem;
}
<div class="container">
<div class="item item-1">1</div>
<div class="item item-2">2</div>
<div class="item item-3">3</div>
<div class="item item-4">4</div>
</div>
最佳答案
您应该使用auto-fill
而不是auto-fit
。不同之处在于,auto-fill
用尽可能多的列填充行,而 auto-fit
扩展列以适应可用空间。
我创建了这个 jsfiddle有解决方案。
grid-template-columns: repeat(auto-fill, minmax(25rem, 1fr));
关于html - minmax 行为,灵活的 css 网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56125458/