弹性项目是否可以与它们上方的项目紧密对齐? [英] Is it possible for flex items to align tightly to the items above them?

查看:34
本文介绍了弹性项目是否可以与它们上方的项目紧密对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实际上就是 Pinterest 布局.然而,网上找到的解决方案是用列包裹的,这意味着容器在不经意间横向增长.这不是 Pinterest 布局,它不适用于动态加载的内容.

我想要做的是一堆固定宽度和不对称高度的图像,水平放置但在满足固定宽度容器的限制时换行:

flexbox 可以做到这一点,还是我必须求助于像 Masonry 这样的 JS 解决方案?

解决方案

Flexbox 是一个一维"布局系统:它可以沿水平或垂直线对齐项目.

真正的网格系统是二维的":它可以沿水平和垂直线对齐项目.换句话说,单元格可以跨列和跨行,而 flexbox 则无法做到.

这就是 flexbox 构建网格的能力有限的原因.这也是

注意上面的 div #3 如何包裹在 div #1 下方,创建一个新行.它不能在 div #2 下换行.

因此,当项目不是行中最高的时,会保留空白,从而产生难看的间隙.

图片来源:Jefree Sujit<小时>

列换行解决方案

如果您切换到 flex-flow: column wrap,弹性项目将垂直堆叠并且更容易实现类似网格的布局.但是,列方向容器立即存在三个潜在问题:

  1. 它水平扩展容器,而不是垂直扩展(如 Pinterest 布局).
  2. 它要求容器具有固定的高度,以便物品知道要包装的位置.
  3. 在撰写本文时,它在所有主要浏览器中都存在缺陷,其中容器无法扩展以容纳额外的列.

因此,列向容器在许多情况下可能不可行.

<小时>

其他解决方案

This is, in effect, the Pinterest layout. However, the solutions found online are wrapped in columns, which means the container inadvertently grows horizontally. That is not the Pinterest layout, and it does not work well with dynamically-loaded content.

What I want to do is have a bunch of images of fixed width and asymmetrical height, laid out horizontally but wrapping in a new row when the limits of the fixed-width container are met:

Can flexbox do this, or do I have to resort to a JS solution like Masonry?

解决方案

Flexbox is a "1-dimensional" layout system: It can align items along horizontal OR vertical lines.

A true grid system is "2-dimensional": It can align items along horizontal AND vertical lines. In other words, cells can span across columns and rows, which flexbox cannot do.

This is why flexbox has a limited capacity for building grids. It's also a reason why the W3C has developed another CSS3 technology, Grid Layout (see below).


In a flex container with flex-flow: row wrap, flex items must wrap to new rows.

This means that a flex item cannot wrap under another item in the same row.

Notice above how div #3 wraps below div #1, creating a new row. It cannot wrap beneath div #2.

As a result, when items aren't the tallest in the row, white space remains, creating unsightly gaps.

image credit: Jefree Sujit


column wrap Solution

If you switch to flex-flow: column wrap, flex items will stack vertically and a grid-like layout is more attainable. However, a column-direction container has three potential problems right off the bat:

  1. It expands the container horizontally, not vertically (like the Pinterest layout).
  2. It requires the container to have a fixed height, so the items know where to wrap.
  3. As of this writing, it has a deficiency in all major browsers where the container doesn't expand to accommodate additional columns.

As a result, a column-direction container may not be feasible in many cases.


Other Solutions

这篇关于弹性项目是否可以与它们上方的项目紧密对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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