这实际上是 Pinterest 布局。但是网上找到的解决方案都是用列包裹的,这意味着容器会在不经意间横向增长。这不是 Pinterest 布局,并且它不适用于动态加载的内容。
我想要做的是有一堆固定宽度和不对称高度的图像,水平放置,但在满足固定宽度容器的限制时换行:
flexbox 可以做到这一点,还是我必须求助于像 Masonry 这样的 JS 解决方案?
最佳答案
Flexbox 是一个“一维”布局系统:它可以沿水平或垂直线对齐元素。
真正的网格系统是“二维”的:它可以沿水平线和垂直线对齐元素。换句话说,单元格可以跨越列和行,这是 flexbox 做不到的。
这就是为什么 flexbox 构建网格的能力有限。这也是 W3C 的原因开发了另一种 CSS3 技术,网格布局(见下文)。
在带有 flex-flow: row wrap
的 flex 容器中, flex 元素必须换行到新的行。
这意味着 flex 元素不能包裹在同一行中的另一个元素之下。
请注意上面的 div #3 如何在 div #1 下方换行,从而创建一个新行。它不能包裹在 div #2 下。
因此,当元素不是行中最高的时候,空白仍然存在,造成难看的间隙。
图片来源:Jefree Sujit
列换行
解决方案
如果您切换到 flex-flow: column wrap
,flex 元素将垂直堆叠并且更容易实现类似网格的布局。然而,列向容器立即存在三个潜在问题:
- 它水平扩展容器,而不是垂直扩展(类似于 Pinterest 布局)。
- > It requires the container to have a fixed height, so the items know where to wrap.
- 在撰写本文时,它在所有主要浏览器中都存在缺陷 the container doesn't expand to accommodate additional columns .
因此,列方向容器在许多情况下可能不可行。
其他解决方案
添加容器
在上面的前两张图片中,考虑将商品 2 和商品 3 包装在一个单独的容器中。这个新容器可以是元素 1 的兄弟容器。完成。
这是一个详细的例子:Calculator keypad layout with flexbox
一个值得强调的缺点:如果您想使用
order
属性重新安排您的布局(例如在媒体查询中),此方法可能会消除该选项。-
Masonry is a JavaScript grid layout library. It works by placing elements in optimal position based on available vertical space, sort of like a mason fitting stones in a wall.
source: http://masonry.desandro.com/
How to Build a Site that Works Like Pinterest
[Pinterest] really is a cool site, but what I find interesting is how these pinboards are laid out... So the purpose of this tutorial is to re-create this responsive block effect ourselves...
source: https://benholland.me/javascript/2012/02/20/how-to-build-a-site-that-works-like-pinterest.html
CSS Grid Layout Module Level 1
This CSS module defines a two-dimensional grid-based layout system, optimized for user interface design. In the grid layout model, the children of a grid container can be positioned into arbitrary slots in a predefined flexible or fixed-size layout grid.
网格布局示例:CSS-only masonry layout but with elements ordered horizontally
关于javascript - flex 元素是否有可能与它们上方的元素紧密对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49740309/