首页 > 解决方案 > 在列中拆分时使用 flexbox 等高“行”

问题描述

不太清楚这个问题该怎么说。我想要做的是允许在列中堆叠标签/数据对的布局。所以标记可能是:

<div>
    <div class="label">hello</div>
    <div class="data">world</div>
<div>

我想要等宽列中的倍数,所以我使用 flexbox 并最终得到如下内容:

hello        hello        hello

world        world        world

这给了我一个很好的视觉效果,并且易于访问,因为标签/对在标记流中一起读取。

工作正常。现在,问题是:标签可能会变得很长。所以我最终得到了这样的结果:

hello        hello this   hello
             is a really
world        long label   world      

             world     

我真正想要的是:

hello        hello this   hello
             is a really
             long label              

world        world        world     

这对 flexbox 可行吗?我试图想出一些东西,但它并不完全存在:

http://jsfiddle.net/0Lfqaj82

我的直觉说不,这是不可能的,因为每列中的每一行都不了解相邻列中行的高度。但是当我对我学到的每一个新的 flexbox 感到惊讶时,我想我会问。

我意识到我可以通过将所有标签放在一行列中并将所有数据放在单独的一行列中来完成这项工作,然后也许使用一些 ARIA 属性将它们绑定在一起以实现可访问性。也许这是最好的解决方案?

标签: cssflexboxmultiple-columns

解决方案


进行两次调整以使布局正常工作。

将此添加到您的代码中:

.flex-rows {
   flex: 1; /* gives this container the height of its parent */
}

.row-flex:last-child {
   margin-top: auto; /* spaces siblings away to the extremes;
                       .row-flex:first-child { margin-bottom: auto } would also work;
                        and so would justify-content: space-between on the container
                        (which would save you from having to create this new rule; */
}

在下面的修改后的代码中,我已经注释掉了看似不必要的规则。

.flex-cols {
  display: flex;
  /* width: 100%; */
  /* flex-direction: row; */
}

.col-flex {
  display: flex;
  flex: 1;
  /* flex-basis: 100%; */
  flex-direction: column;
  margin-right: 20px;
  border: 1px solid green;
  padding: 5px;
}

.flex-rows {
  flex: 1; /* ADDITION #1 */
  display: flex;
  /* width: 100%; */
  flex-direction: column;
}

.row-flex {
  border: 1px solid red;
  display: flex;
  /* flex: 1; */
  /* flex-basis: 100%; */
  flex-direction: column;
  margin-bottom: 20px;
}

.row-flex:last-child {
    margin-top: auto; /* ADDITION #2 */
}
<div class="flex-cols">
  <div class="col-flex">
    <div class="flex-rows">
      <div class="row-flex">
        Hello
      </div>
      <div class="row-flex">
        World
      </div>
    </div>
  </div>
  <div class="col-flex">
    <div class="flex-rows">
      <div class="row-flex">
        Hello, hello, hello! This is a bunch of extra text to explain what should happen. Ideally, this will take up as much room as needed, and the div below will take up an equal amount to force a vertical 50/50 split.
      </div>
      <div class="row-flex">
        World
      </div>
    </div>
  </div>
   <div class="col-flex">
    <div class="flex-rows">
      <div class="row-flex">
        Hello
      </div>
      <div class="row-flex">
        World
      </div>
    </div>
  </div>
</div>

jsFiddle 演示


推荐阅读