最终,一个仅使用 CSS 的解决方案可以创建砌体布局

2025-06-08

最终,一个仅使用 CSS 的解决方案可以创建砌体布局

稍等!以下功能尚处于实验阶段,只能在 Firefox 上测试

CSS Grid Level 3的规范实际上正在构建中,它是关于砌体布局的

该模块引入了砌体布局作为 CSS Grid 容器的附加布局模式。

砌体到底是什么?

这就是你在浏览 Pinterest 时看到的内容。类似下图:

砌体布局
图片取自链接的规范

我们过去常常使用 JS 或大量的 CSS 来构建它,但现在只需一个 CSS 属性就可以做到这一点。

.container {
  grid-template-rows: masonry; 
}
Enter fullscreen mode Exit fullscreen mode

有,仅此而已!

完整代码如下:

<div class="container">
  <img src="https://picsum.photos/id/1/200/300">
  <img src="https://picsum.photos/id/17/200/400">
  <img src="https://picsum.photos/id/18/200/100">
  <img src="https://picsum.photos/id/109/200/200">
  <img src="https://picsum.photos/id/1069/200/600">
  <img src="https://picsum.photos/id/120/200/150">
  <img src="https://picsum.photos/id/130/200/100">
  <img src="https://picsum.photos/id/203/200/100">
  <img src="https://picsum.photos/id/109/200/200">
  <img src="https://picsum.photos/id/11/200/100">
  <img src="https://picsum.photos/id/119/200/100">
</div>
Enter fullscreen mode Exit fullscreen mode
.container {
  display: grid;
  grid-template-columns: repeat(auto-fil, minmax(200px, 1fr));
  grid-template-rows: masonry; /* this will do the magic */
  grid-gap: 10px;
}
img {
  width:100%;
}
Enter fullscreen mode Exit fullscreen mode

您可以在 Firefox 上测试上述内容,但您需要首先启用一个标志:

  1. 打开 Firefox 并about:config在 URL 栏中输入
  2. 使用以下方式进行搜索masonry
  3. 你会得到一面旗帜,让它成为现实

旗帜

您应该会得到以下结果:

砌体布局

由于repeat(auto-fil, minmax(200px, 1fr))

CSS砌体

我们还可以通过调整 CSS 来实现其他方向,如下所示:

.container {
  display: grid;
  grid-template-rows: repeat(auto-fil, minmax(200px, 1fr));
  grid-template-columns: masonry; 
  grid-gap: 10px;
  height:100vh;
}
img {
  height:100%;
}
Enter fullscreen mode Exit fullscreen mode

砌体水平

该规范引入了许多其他属性来控制我们的砌体网格,但现在研究它们还为时过早,因为它们可能随时发生变化。

值得注意的是,CSS Grid Level 2仍未被所有浏览器完全实现,因此我们需要耐心等待 Level 3 的实现。

鏂囩珷鏉ユ簮锛�https://dev.to/afif/finally-a-css-only-solution-to-create-masonry-layouts-1obh
PREV
JavaScript 中的函数柯里化
NEXT
超级赛亚人 CSS 艺术!