如何使CSS网格中的图像在缺少空间时并排放置并跳到另一行 [英] How to make images in a CSS Grid lay next to each other and jump to another row when lacking space

查看:16
本文介绍了如何使CSS网格中的图像在缺少空间时并排放置并跳到另一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用CSS网格以图片中所示的方式放置图像,但找不到正确的解决方案。

现在我只是简单地将网格流动更改为列,但网格元素在遇到容器的末尾时不会跳到另一行-它们会调整容器的大小并保持在相同的第一行。

我尝试使用grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr))-它解决了跳转到另一行的问题,但它为所有元素提供了固定的宽度,而某些图像并不是那么宽。它会在图像之间造成空洞,这是我想要避免的。

您对如何实现这一目标有什么想法吗?

wrong solution 1

上图中的代码:

container {
            display: grid;
            grid-gap: 1rem;
            grid-auto-flow: column;
        }
photo { // all container's elements have this class
            height: 10rem;
            width: auto;
        }

wrong solution 2

上图中的代码:

container {
            display: grid;
            grid-gap: 1rem;
            grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
        }

photo {
         height: 10rem;
         max-width: 100%;
      }

推荐答案

您看,这是flex的象牙,不是grid的象牙。使用grid表示每行具有相同宽度的列。这里根本不需要。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
html {
  font-size: 10px;
}
.conteiner {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.photo {
  height: 10rem;
  margin: 0 1rem 1rem 0;
}
.photo img {
  width: auto;
  height: 100%;
}
<div class="conteiner">
  <div class="photo"><img src="https://via.placeholder.com/500x200"></div>
  <div class="photo"><img src="https://via.placeholder.com/300x200"></div>
  <div class="photo"><img src="https://via.placeholder.com/200x200"></div>
  <div class="photo"><img src="https://via.placeholder.com/400x200"></div>
  <div class="photo"><img src="https://via.placeholder.com/500x200"></div>
  <div class="photo"><img src="https://via.placeholder.com/300x200"></div>
  <div class="photo"><img src="https://via.placeholder.com/200x200"></div>
</div>

虽然我使用的是Justified galleryjQuery插件,但如果我想要每行中的所有图像来填充所有宽度。

这篇关于如何使CSS网格中的图像在缺少空间时并排放置并跳到另一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆