我需要显示一个带有方形图像的简单网格。我惊讶地发现,当图像是网格的直接子级时,它无法正常工作。图像变得太大,相互重叠。
.grid {
display: grid;
gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
}
img {
aspect-ratio: 1 / 1;
background-color: orange;
object-fit: contain;
}
<div class="grid">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
</div>
如果我申请width: 100%
和height: 100%
to ,它可以正常工作img
,但我试图理解为什么。
是否有一些额外的方法来处理网格内的图像大小?当网格已经指示它们时,为什么它们需要明确的尺寸?
网格在哪里提供这些说明?事实并非如此。
您的规则
grid-template-columns: repeat(auto-fit, minmax(400px, 1fr))
设置了列。它不适用于这些列内的内容。width: 100%
在不添加图像的情况下,它们会计算其固有尺寸,在本例中为 1920 x 1080。作为 HTML/CSS 的一般做法,添加内容
img { width: 100%; height: auto }
以防止图像溢出其容器。