使弹性项目包装在列方向的容器中 [英] Make flex items wrap in a column-direction container

查看:48
本文介绍了使弹性项目包装在列方向的容器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,要使用行布局将元素包装在flex div中,我要做的就是:

So, to wrap elements in a flex div using a row layout all I have to do is this:

div {
  display: flex;
  flex-direction: row;  /* I want to change this to column */
  flex-wrap: wrap;      /* wrap doesn't seem to work on column, only row */
}

<div>
  <p>these</p>
  <p>will</p>
  <p>wrap</p>
</div>

这适用于我的行,但我也想使其适用于我的列.

This works for my rows, but I want to make it work for my columns as well.

我尝试仅将 flex-direction 更改为 column ,但是它似乎不起作用.有谁知道如何获得此功能?

I tried just changing flex-direction to column, but it doesn't seem to be working. Does anyone know how to get this functionality?

推荐答案

默认情况下,块级元素占用其包含块的完整宽度.实际上,这可以解析为 width:100%,这将在水平方向上中断内容流.

Block-level elements, by default, take up the full width of their containing block. This, in effect, resolves to width: 100%, which sets a break in the flow of content in the horizontal direction.

因此,默认情况下,伸缩项可以包装在行方向容器中.

So, flex items can wrap by default in a row-direction container.

但是,HTML或CSS中的任何内容都不会在块级元素上设置默认高度.高度受内容驱动( height:auto ).

Nothing in HTML or CSS, however, sets a default height on block-level elements. Heights are content-driven (height: auto).

这意味着元素将垂直流动而没有任何破裂的理由.

This means that elements will flow vertically without having any reason to break.

(我猜想可能是在可用性研究的基础上发展的某个方向,因此确定Web应用程序垂直扩展而不是水平扩展是可以的.)

(I guess somewhere along the line of evolution, possibly on the basis of usability studies, it was decided that it would be okay for web applications to expand vertically, but not horizontally.)

这就是为什么flexbox不会自动在列方向上包装项目的原因.它需要作者定义的高度作为断点.

That's why flexbox doesn't automatically wrap items in column direction. It requires an author-defined height to serve as a breaking point.

但是,布局的高度通常是动态的,因此无法设置特定的高度.这使得flexbox无法用于在列方向上包装项目.CSS 网格布局是一种很好的选择,它不需要高度在容器上设置:

Often times, however, a layout's height is dynamic so a specific height cannot be set. That makes flexbox unusable for wrapping items in column direction. A great alternative is CSS Grid Layout, which doesn't require a height setting on the container:

div {
  display: grid;
  grid-gap: 10px;
}

p:nth-child(3n + 1) {
  grid-row: 1;
  background-color: aqua;
}

p:nth-child(3n + 2) {
  grid-row: 2;
  background-color: orange;
}

p:nth-child(3n + 3) {
  grid-row: 3;
  background-color: lightgreen;
}

p {
  margin: 0;
  padding: 10px;
}

<div>
  <p>ONE</p>
  <p>TWO</p>
  <p>THREE</p>
  <p>FOUR</p>
  <p>FIVE</p>
  <p>SIX</p>
  <p>SEVEN</p>
  <p>EIGHT</p>
  <p>NINE</p>
</div>

对CSS网格的浏览器支持

  • Chrome-截至2017年3月8日(版本57)全面支持
  • Firefox-截至2017年3月6日(版本52)全面支持
  • Safari-截至2017年3月26日(版本10.1)全面支持
  • Edge-截至2017年10月16日(版本16)全面支持
  • IE11-不支持当前规范;支持过时的版本

这是完整的图片: http://caniuse.com/#search=grid

这篇关于使弹性项目包装在列方向的容器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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