网格中的图像不随视窗缩放



如果我将图像放入CSS网格中,即如果图像充当网格项,则它们不会随视窗缩放,否则会发生这种情况。(这只是4张大小相等的图片)

.imgContainer {
display: grid;
grid-template-columns: 196px 196px;
grid-gap: 12px;
justify-content: center;
}
.imgContainer img{
max-width: 100%;
height: auto;
}

如果我理解对了…试着这样写:

grid-template-columns: 50% 50%;

而不是:

grid-template-columns: 196px 196px;

所以图像是可伸缩的

由于您将网格单元格的高度限制为196px,因此图像没有响应大小。由于您在grid-template-columns声明中使用了像px这样的绝对长度单位,这就是它们不调整大小的原因。它们只是像预期的那样占据了所有的网格项目空间。您可以在列定义中使用相对长度单位,如%,vw等或repeat(minmax())来修复此问题。

使图像随视窗缩放或者创建一个具有动态确定尺寸的网格项的响应网格,我倾向于将repeat()minmax()配对。允许图像占用父网格项并随之增长/缩小。您只需要调整grid-template-columns的使用。您可以单独使用50% 50%为您的列,使他们与视窗缩放或使用repeat()使用我已经定义了一个max-width在父网格。

.imgContainer {
display: grid;
grid-template-columns: 50% 50%; /* Using relative length units */
grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr));
grid-gap: 12px;
justify-content: center;
max-width: 80ch;
}
.imgContainer img {
max-width: 100%;
height: auto;
}
<section class="imgContainer">
<div class="item"><img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/cute-cat-photos-1593441022.jpg?crop=0.669xw:1.00xh;0.166xw,0&resize=640:*" alt="cat photo" /></div>
<div class="item"><img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/cute-cat-photos-1593441022.jpg?crop=0.669xw:1.00xh;0.166xw,0&resize=640:*" alt="cat photo" /></div>
<div class="item"><img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/cute-cat-photos-1593441022.jpg?crop=0.669xw:1.00xh;0.166xw,0&resize=640:*" alt="cat photo" /></div>
<div class="item"><img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/cute-cat-photos-1593441022.jpg?crop=0.669xw:1.00xh;0.166xw,0&resize=640:*" alt="cat photo" /></div>
</section>

最新更新