Make flex items wrap in a column-direction container

无人久伴 提交于 2021-01-01 07:15:39

问题


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.

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


回答1:


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.

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.

(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.)

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


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>

Browser Support for CSS Grid

  • Chrome - full support as of March 8, 2017 (version 57)
  • Firefox - full support as of March 6, 2017 (version 52)
  • Safari - full support as of March 26, 2017 (version 10.1)
  • Edge - full support as of October 16, 2017 (version 16)
  • IE11 - no support for current spec; supports obsolete version

Here's the complete picture: http://caniuse.com/#search=grid



来源:https://stackoverflow.com/questions/43834172/make-flex-items-wrap-in-a-column-direction-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!