作者:谢海武181_160 | 来源:互联网 | 2022-12-09 12:23
我的目标是创建一个响应网格,其中包含未知数量的项目,其长宽比保持在16:9。现在看起来像这样:
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, 160px);
grid-template-rows: 1fr;
grid-gap: 20px;
}
.item {
height: 90px;
background: grey;
}
问题在于,这些项目不会随屏幕尺寸缩放,从而在正确的位置留出空白。但是,当使用例如:使网格适应屏幕尺寸grid-template-columns: repeat(auto-fit, minmax(160p, 1fr))
并删除时height: 90px;
,长宽比不会持久。
如果没有CSS网格,也许有更好的解决方案?(也许使用Javascript)
1> Danield..:
您可以利用以下事实:百分比填充基于宽度。
这篇CSS技巧文章很好地解释了这个想法:
...如果元素的宽度为500px,且padding-top为100%,则padding-top为500px。
那不是500px×500px的完美正方形吗?是的!长宽比!
如果我们强制元素的高度为零(高度:0;)并且没有任何边界。然后,填充将成为影响高度的盒子模型的唯一部分,我们将得到正方形。
现在想象一下,我们使用56.25%代替100%顶部填充。碰巧是完美的16:9比例!(9/16 = 0.5625)。
因此,为了使列保持长宽比:
1)根据您的建议设置列宽:
grid-template-columns: repeat(auto-fit, minmax(160p, 1fr))
2)在项目中添加一个伪元素以保持16:9的宽高比:
.item:before {
content: "";
display: block;
height: 0;
width: 0;
padding-bottom: calc(9/16 * 100%);
}
.item:before {
content: "";
display: block;
height: 0;
width: 0;
padding-bottom: calc(9/16 * 100%);
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
grid-template-rows: 1fr;
grid-gap: 20px;
}
.item {
background: grey;
display: flex;
justify-content: center;
}
.item:before {
content: "";
display: block;
height: 0;
width: 0;
padding-bottom: calc(9/16 * 100%);
}