我正在尝试创建砌体布局使用 css 网格布局。网格中的所有元素都具有可变 高度。而且我不知道会是什么元素。所以我无法为每个元素定义 grid-row
。是否可以在列中上一个元素结束后立即开始每个新元素?
我正在尝试的代码:
.wrapper {
display: grid;
grid-template-columns: repeat(auto-fill, 330px);
align-items: flex-start;
grid-column-gap: 10px;
grid-row-gap: 50px;
}
.item {
background: black;
border-radius: 5px;
}
<div class="wrapper">
<div class="item" style="height:50px"></div>
<div class="item" style="height:100px"></div>
<div class="item" style="height:30px"></div>
<div class="item" style="height:90px"></div>
<div class="item" style="height:80px"></div>
<div class="item" style="height:50px"></div>
<div class="item" style="height:70px"></div>
<div class="item" style="height:40px"></div>
</div>
最佳答案
在您的问题中,您要单独设置每个元素的高度。如果您乐于这样做,那么可以使用网格轻松实现 Masonry 布局。
而不是为每个元素设置高度 grid-row-end
以便每个元素跨越一定数量的行。
<div class="item" style="grid-row-end: span 5"></div>
元素的高度将取决于您为网格设置的 grid-auto-rows
和 grid-row-gap
的值。
我在这里做了一个代码笔:https://codepen.io/andybarefoot/pen/NaprOB
如果您不想为每个元素单独设置 grid-row-end
值,您可以使用一些 JavaScript 来动态地完成它。我在每个元素中放置了另一个“容器”div,并测量该容器的高度以计算该元素需要跨越多少行。我在页面加载时执行此操作,并在加载任何图像时对每个元素再次执行此操作(因为内容的高度将发生变化)。如果您将这种方法与响应式布局结合使用,那么您还应该重新计算页面大小调整,因为列的宽度可能已经改变,这将影响内容的高度。
这是我调整响应列大小的完整示例:https://codepen.io/andybarefoot/pen/QMeZda
如果您有宽度可变的元素,您仍然可以获得类似的效果,但网格的包装不会完美,并且元素顺序可能会更改以优化包装。
我在 Medium 上写了一篇关于这种方法的博客,以防有人感兴趣:A Masonry style layout using CSS Grid
关于css - 带有 CSS 网格的砌体布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43917346/